Node.js - xerocrypt/Misc GitHub Wiki

Server-Side JavaScript Framework, or a JavaScript runtime environment. Node.js was introduced in 2009/2010, but is already widely used and well-supported.

The main purpose of Node.js is to enable the creation of Web servers and associated network tools using JavaScript, and there are additional modules for performing server-side operations. Node.js enables communication between the client-side JavaScript and the server.

A Node.js application has the following:

  • Module imports
  • Server creation
  • Response

Creating a Simple Server The server-side code for this is simple. First line imports the http module:

var http = require("http");

The following lines create the server using createServer(). Within this, we want to define the server response for client browsers starting a session on port 8090:

http.createServer(function (request, response)

{

`response.writeHead(200, {'Content-Type': 'text/plain'});`

`response.end('Hello World\n');`

}).listen(8090);

Also, we might want a response sent to the command line to indicate the server is started: console.log('Server running at http://127.0.0.1:8090/');

File Operations

Perhaps the main reason we want server-side code, rather than something entirely client-based is data persistence - storing and retrieving data on a server is a core feature of a Web application.

Here I have two files: file-op.js server-side script, and the serverdata.txt data file. The latter simply contains two lines of text.

This time we import both the http and filesystem (fs) modules:

var http = require("http");

var fs = require("fs");

And specify the file to read:

var data = fs.readFileSync('serverdata.txt');

And this time, the HTTP response is defined as the contents of serverdata.txt:

http.createServer(function (request, response)

{

`response.writeHead(200, {'Content-Type': 'text/plain'});`

`response.end(data.toString());`

}).listen(8090);

References

Node.js Home

TurorialsPoint Node.js Introduction