Run a server from Node.js

Step 1: Download and install Node.js from https://nodejs.org/en/

Step 2: Launch node from command prompt and verify it has installed correctly

Step 3: Create a new file server.js as follows:

var http = require('http');
var fs = require('fs');
var url = require('url');

http.createServer( function (request, response)
{
   var pathname = url.parse(request.url).pathname;
   fs.readFile(pathname.substr(1), function (err, data)
   {
      if (err)
      {
         console.log(err);
         response.writeHead(404, {'Content-Type': 'text/html'});
         response.write(err.toString());
      }
      else
      {   
         response.writeHead(200, {'Content-Type': 'text/html'});   
         response.write(data.toString());       
      }
      response.end();
   });  
}).listen(8844);

console.log('Server running at http://127.0.0.1:8844/');

Step 4: Open command prompt and change to directory where you have saved server.js

Step 5: Run node server.js from command prompt

Step 6: Now open browser and go to localhost:8844 and it will open your homepage

This walkthrough starts a basic web server in Node.js using the built in http module to serve files from disk. It is the classic first step for learning server side JavaScript.

The built in modules are enough for a minimal server, while frameworks such as Express add routing and middleware once the project grows beyond a few endpoints.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram