2

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); 
4
  • 2
    console.log('print in browser console ') <- that code is running on the server, not in the browser. Commented Nov 12, 2021 at 12:00
  • 1
    You cannot show logs you are printing in the server in the browser, it is just impossible because code is executing in different machines. Commented Nov 12, 2021 at 12:00
  • @A.Llorente I didn't get it, can't we run in browser, however we r running at 4000 port Commented Nov 12, 2021 at 12:05
  • 1
    Yes, but you run the server on port 4000 and you are showing the console (that's one machine) and then you access it through your browser (other machine). The fact that your server is running on the same hardware as your client doesn't make them the same "machine", or better called "execution environments" Commented Nov 12, 2021 at 12:06

3 Answers 3

5

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 ********/
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.