Hemanth's Scribes

node

Launch Browser from Node Server

Author Photo

Hemanth HM

Thumbnail

Why launch browser from a Node server?

  • Because we are lazy!
  • For quick demos
  • Quick testing
  • Less manual work

The Code

var http = require('http'),
    open = require('open'),
    server;

server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

server.listen(1337, '127.0.0.1', function() {
  console.log('Launching the browser!');
  open('http://127.0.0.1:1337');
});

The only dependency is open which opens a file or URI with the user’s preferred application (browser, editor, etc), cross platform.

npm install open

In server.listen(port, [host], [backlog], [callback]), the callback is added as a listener for the listening event - perfect for knowing when to launch the browser!

#node#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.