Introduction to Node.js Commands
Node.js is a cross-platform, fast and lean JavaScript runtime environment built on a JavaScript engine. Node.js uses an event-driven, non-blocking I/O by which we can achieve low latency and high throughput and makes it lightweight and efficient. Node.js will be useful for both servers and desktop applications. Node.js is written in C/C++, JavaScript, and its package ecosystem NPM (node package manager), which consists of a large number of open source libraries in the package. Node.js was introduced in 2009 by Ryan Dahl for Linux and Mac OS and now runs on different platforms like Windows, UNIX, Linux, Mac OS X, etc. It uses JavaScript on the server. Now we will discuss the Node.js Commands in detail.
Basic Node.js Commands
Following are some basic commands of node.js:
1. Program to display hello world using Node.js?
We can write a program in node.js to print hello world as below.
We need to create a file named “hello.js” and write the below code
Code:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
By accessing port 8080 using the link http://localhost:8080/, we will see hello world.
Output:
2. How to create a user module in node.js and use it?
We can create our own model in node.js as below.
exports.myDateTime = function () {
return Date();
};
Now we can use the above module in our code and access through the port 8080 as below code:
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Output: /summer
3. How to create a web server in node.js?
Code:
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
Output: /summer
4. How to add HTTP header in node.js and when to add?
We need to add an HTTP header when the server is supposed to display the content in HTML format; then we can use the HTTP header with content we need as below:
Code:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
Output: /summer
5. How to read the query string in node.js?
In order to read the query string in node.js, we need to implement as below code where the create-server() function has a request parameter/argument, which represents an argument from a client as an object.
Code:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
We can initiate as below: node demo_http_url.js
Output: /summer
6. How to split the query string in node.js?
We can split the query string in node.js using the URL module and the code as below.
Code:
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);<
Output:
7. How to read a file in node.js?
We can read a file in node.js using the readFile() method as below.
Code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
Output:
8. How to create an empty file using an open method in node.js?
We can create an empty file using the open method in node.js as below.
Code:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
Output:
9. How to update an existing file in node.js?
We can update the existing file in node.js as below.
Code:
var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
if (err) throw err;
console.log('Updated!');
});
Output:
10. How to replace the existing content in a file in node.js?
We can replace the existing content in a file in node.js using the writeFile() method as below.
Code:
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Output:
Intermediate Node.js Commands
Following are some intermediate commands of node.js:
1. How to trigger a report on the fatal error in node.js?
We can trigger a report of a fatal error using the command line option
–diagnostic-report-on-fatalerror
The above node.js command enables the report on the fatal error, terminates the application, and is useful for inspecting various diagnostics.
2. What is the use of a console class in node.js, and how to use it?
The console class in node.js is used as a debugging console similar to in JavaScript, and the console class in node.js has three methods console.log(), console.error(), and console.warn() are used to write to any node.js streams.
3. How to create a new console in node.js with an example?
We can create a new console in node.js as below:
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
const logger = new Console({ stdout: output, stderr: errorOutput });
const count =5;
logger.log(‘count:%d’,count);
4. How to certificate class in node.js with an example?
We can use certificate class in node.js with the help of crypto module in node.js as it provides certificate class and with which we can able to work with SPKAC data and mostly used for handling output from HTML5 <keygen> element.
5. How to create a new instance of a certificate class in node.js?
The new instance of a certificate class can be created using the new keyword in node.js as below:
const crypto = require(‘crypto’);
const cert1 = new crypto.Certificate();
const cert2 = crypto.Certificate();
Advanced Node.js Commands
Following are some advanced commands of node.js:
1. How to pass arguments to the listener function in node.js?
We can pass arguments and this keyword to the listener functions as below:
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
// Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');
2. Explain Asynchronous and Synchronous calls in node.js?
In node.js, EventEmitter calls all listeners synchronously in which order they registered as it is important to maintain proper sequence to avoid race conditions, and listener functions can switch to an asynchronous mode of operation using methods such as setImmediate() or process.nextTick()
myEmitter.on('event', (a, b) => {
setImmediate(() => {
console.log('this happens asynchronously');
});
});
myEmitter.emit('event', 'a', 'b');
Tips and Tricks to use Node.js Commands
- Use the asynchronous code and try to avoid using the synchronous code.
- Always have a check for errors – never throw any errors and miss to catch the errors.
- Good to know about npm – you can know by installing modules with –S and –D options.
- Use exact versions only in package.json –By default, npm adds caret when option –S is used, and we need to manually edit to use exact versions, and with open source modules, we can use directly.
Conclusion
Finally, it’s a conclusion about different types of node.js commands and some tips and tricks to use them. I hope you will have a good understanding of node.js commands and how to use them after reading this article.
Recommended Articles
This has been a guide to Node.js Commands. Here we have discussed basic, intermediate as well as advanced Node.js commands along with tips and tricks to use those commands. You may also look at the following article to learn more-