Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Launch Browser From Node Server

| Comments

About 400 days ago I had blogged about live reload with grunt which explained about auto refreshing the browser on any change that occurs on the file that is being observed. Here I would like to talk about a simple way to launch the browser from a node webserver.

Why do you need that? :

  • Because we are lazy!
  • For quick demos.
  • Quick Testing.
  • Less of manual work.

Let's see the code!:

1
2
3
4
5
6
7
8
9
10
11
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 users preferred application (browser, editor, etc), cross platform. [ npm install open ] In the node API server.listen(port, [host], [backlog], [callback]) the last parameter callback will be added as an listener for the listening event, which is useful in identifying that the server is up and it's the right time to launch the browser!

Comments