My first Node.JS Code

Firstly I created a file called: main.js

 The first line I wrote was the http library being called to the file. This standard http library allows me to make http.createServer function later on for me to listen to a port 8080 for any requests.

I wrote a variable called "body" and added a string of text that I want to show on when I accessed localhost:8080 on the web browser.

The res.writeHead(...) function, available as a local library of Nodejs, allowed me to write some file headers that will be showned when I run the curl -i command later.
Content-Length and Content-Type are the header information that I add to the webpage. There are many header variables that we can add which I will describe in detail in other posts. The 200 server response code passed in res.writeHead(..,..) first argument is a success response code.
var http = require('http');

function process_request(req, res) {
   
    var body = "This is the body of a Javascript code.";

    var content_length = body.length;

    res.writeHead(200, {
        'Content-Length': content_length,
        'Content-Type': 'text/plain'
    });

    res.end(body);
}
var s = http.createServer(process_request);

s.listen(8080);

Using
node main.js

This is the result I received from running the code using the command given above.


HTTP/1.1 200 OK
Content-Length: 38
Content-Type: text/plain
Date: Tue, 05 Dec 2017 10:03:53 GMT
Connection: keep-alive

This is the body of a Javascript code.

If I accessed the website from a Mozilla Firefox browser, I will only get:
 This is the body of a Javascript code.

on the webpage.

Comments