Basic server

Usage

node [options] [v8 options] [script.js | -e "script" | - ] [arguments]

Example

An example of a web server written with Node.js which responds with 'Hello World':

const http = require('http');

 

const hostname = '127.0.0.1';

const port = 3000;

 

const server = http.createServer((req, res) => {

  res.statusCode = 200;

  res.setHeader('Content-Type', 'text/plain');

  res.end('Hello World\n');

});

server.listen(port, hostname, () => {

  console.log(`Server running at http://${hostname}:${port}/`);

});

To run the server, put the code into a file called example.js and execute it with Node.js:

$ node example.js

Server running at http://127.0.0.1:3000/

The http module for your Node.js server

// content of index.js const http = require('http') const port = 3000 const requestHandler = (request, response) => { console.log(request.url) response.end('Hello Node.js Server!') } const server = http.createServer(requestHandler) server.listen(port, (err) => { if (err) { return console.log('something bad happened', err) } console.log(`server is listening on ${port}`) })

You can start it with:

$ node index.js

Express

Adding Express to your project is only an NPM install away:

$ npm install express --save

Once you have Express installed, let's see how you can create a similar application as before:

const express = require('express') const app = express() const port = 3000 app.get('/', (request, response) => { response.send('Hello from Express!') }) app.listen(port, (err) => { if (err) { return console.log('something bad happened', err) } console.log(`server is listening on ${port}`) })