Home > other >  HTTP Server and Console.log at Node js
HTTP Server and Console.log at Node js

Time:11-13

I am new to node js and trying to learn with a few examples, so my requirement is I should get output in browser console mode, I want to check it via HTTP server as well as in console, but data is printed only on browser page but didn't get any console output.

Code:

require('http').createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Data render at browser page');
    console.log('print in browser console ');   
}).listen(4000); 

CodePudding user response:

You can send a HTML response and add a script tag:

/********** Node.js start ********/
/* This code is run in Node.js */
require('http').createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(''  
`<html>
  <head></head>
  <body>
    Data render at browser page
    <script>
      /********** Browser start ********/
      /* This code is run in the browser */
      console.log('print in browser console ');
      /********** Browser end ********/
    </script>
  </body>
</html>`);
    console.log('print in Node.js engine');   
}).listen(4000);
/********** Node.js end ********/

CodePudding user response:

Node Js do not run in the browser so, you can't see any console.log() output to the browser console instead it will show in the terminal.

CodePudding user response:

It's a bit confusing if you are using node.js for the first time because it runs on the server instead of the client browser.

Having said that, is actually now possible to pipe your node console output to the browser console. Please check out this github repo connect-browser-logger on github

You can also use NodeMonkey as mentioned here - Output to Chrome console from Node.js

  • Related