Introduction to Node JS

Node.js is a free open-source server environment that uses JavaScript and that can run on many operating systems like Mac os, windows, and Linux. We use Node.js mainly because unlike other technologies Node.js eliminates the waiting time, and simply continues with the next request. Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory efficient. Node.js file has an extension ".js".
Installing Node.js
You can easily install Node.js into your system by following this link.
Let's quickly understand by doing some basic code.
Create a file named app.js. Here if anyone tries to access port on 8000, the code tells the computer to write Hello World!. We can create an HTTP server that listens to port 8000 and return HTML with Hello World.
const http = require('http'); // Load HTTP module
http.createServer(function (req, res) {
//Set the response HTTP header with HTTP status and Content type
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!'); // response in body
}).listen(8000);
Now if you save, and run node app.js you should see Hello World! on the browser page. Visit http://localhost:8000
Same code using some standard. Here we are using variables for each instance. Now it looks cool!
const http = require("http");
const hostname = "127.0.0.1";
const port = 8000;
const server = http.createServer((req, res) => { // Create HTTP server
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
})
Node has built-in modules that are installed when we install Node.js in our system. We can use these modules using require() function as used in the code above.
Creating own modules
Create a file named test.js and include it in the same directory of app.js. Now add the below code to the test.js.
exports.myDateTime = function () { // test.js
return Date();
};
Modify the code in app.js as below.
const http = require('http');
const test = require('./test');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time - " + test.myDateTime());
res.end();
}).listen(8000);
// If now you visit port 8000 you can get current date & time.
Now you have used your own module in app.js. Now if you visit port 8000 you can get current date & time.
Node.js File System
We can use the Node.js file system to work with the file system on the computer.
Read file: We can use the fs.readFile() method asynchronously to read the file on the computer
const fs = require('fs');
// First we need to create test.txt in the same directory & add some //lines
const fileName = __dirname + '/test.txt';
fs.readFile(fileName, (err, data) => {
if (err){
console.error(err);
}
console.log(data.toString())
})
Create a new file and copy content: We can use Node.js and perform file copying. Here the content in the test.txt will be copied to testnew.txt which will be created after the execution of the code.
//The __dirname in a node script returns the path of the folder //where the current JavaScript file resides.
const fs = require('fs');
const fileName = __dirname + '/test.txt';
const fileNew = __dirname + '/testnew.txt';
const readStream = fs.createReadStream(fileName);
const writeStream = fs.createWriteStream(fileNew);
readStream.pipe(writeStream);
readStream.on('data', data => {
console.log(data.toString());
});
There is more we can do with Node.js, we have covered only the basic implementations.