Main Features of NodeJS
Once we have downloaded and installed Node.js on our computer, let’s try to display “Hello World” in console.
Check the node version of the machine by issuing the following command. node –version
Create a file named app.js.
Use default console log command to print string to the console.
console.log('Hello World');
Type the following command in the command prompt (Command should be opened in the working directory).
node app.js or node app
let’s try to display “Hello World” in browser.
const http = require('http');
http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
switch (req.method) {
case 'GET':
res.write('<h1>Hello World</h1>');
res.end();
break;
case 'POST':
req.on('data', data => {
res.write('<h1>Hello ' + data + '</h1>');
res.end();
});
break;
}
}).listen(3000, (err) => {
console.log('Server is listening to port 3000')
});
we can run these like before
How we can use OS system library
Import the OS system module to your file.
const os = require('os');
Obtain System architecture, platform and number of CPUs from the OS module and print them to the console.
console.log('Architecture ' + os.arch());
console.log('CPUs ' + os.cpus().length);
console.log('OS ' + os.platform());
Read file in nodejs
Create a file named test.txt and add the following content.
NodeJS is awesome.
Import the fs system module to read the file
const fs = require('fs')
Use the system variable __dirname to set the file location
const fileName = './test.txt';
Read the file using readFile asynchronous method and print the content of the file to console
fs.readFile(fileName,(err,data) =>{
if (err) {
console.error(err);
}
console.log(data.toString());
});
Use the readFileSync method to read the file synchronously.
const data = fs.readFileSync(fileName);
console.log(data.toString());
Write to file
Use streams to copy content of a file.
Add two variables containing path to the source and destination files.
const fileName2 = './test.txt';
const OutfileName = './test2.txt';
Create read stream and write stream from the source file and destination file respectively.
const readStream = fs.createReadStream(fileName2);
const writeStream = fs.createWriteStream(OutfileName);
Pipe the read stream to write stream.
readStream.pipe(writeStream);
Optionally listen to the data event of the read stream and print the output.
readStream.on('data', data => {
console.log(data.toString());
});