Node.js Server
Node.js is a javascript framework for writing Server-side applications.
A Node.js server provides the mechanisms for connecting to a service and sending/receiving data. It achieves this through TCP or UDP connections. Developers can hence create their own server and test their app deployment.
NodeJS comes with a simple HTTP server built-in. This HTTP server allows us to listen on an arbitrary port(specified by us) and receive callbacks via a callback function that will be invoked every time a request is made to the server.
The callback will receive two arguments: a Request object and a Response object. The Request object will be filled with useful properties about the request, and the Response object will be used to send a response to the client.
Once you have installed Node, let’s try building our first web server. For example, let us code a server.js file-
const http = require( 'http' ); const hostname = '127.0.0.1' ; const port = 8081; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader( 'Content-Type' , 'text/plain' ); res.end( 'Hello, Welcome to w3wiki !\n' ); }); server.listen(port, hostname, () => { console.log(`Your Node.js server is running at http: //${hostname}:${port}/`); }); |
Now to execute this file from terminal simply write:-
node server.js |
and you’ll see:
And on navigating to the specified url a simple HTML page will open displaying :
Hence, we created a local Node.js web server listening on port 8081.