What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment that enables server-side scripting. It is used for building fast, scalable network applications. Node.js is based on the JavaScript programming language and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Example:

A simple Node.js application that prints “Hello World” to the console can be written as follows:

const http = require(‘http’);

const hostname = ‘127.0.0.1’;
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hello Worldn’);
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

What are the core modules of Node.js?

The core modules of Node.js are:

1. HTTP – This module provides a way of creating an HTTP server and making HTTP requests. Example:

const http = require(‘http’);

const server = http.createServer((req, res) => {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘Hello Worldn’);
});

server.listen(3000);

2. FS – This module provides a way of interacting with the file system. Example:

const fs = require(‘fs’);

fs.readFile(‘/path/to/file’, ‘utf8’, (err, data) => {
if (err) throw err;
console.log(data);
});

3. Path – This module provides utilities for working with file and directory paths. Example:

const path = require(‘path’);

const fileName = path.basename(‘/path/to/file.txt’);
console.log(fileName); // Outputs: file.txt

4. Stream – This module provides a way of streaming data. Example:

const fs = require(‘fs’);
const stream = require(‘stream’);

const readStream = fs.createReadStream(‘/path/to/file.txt’);

const writeStream = new stream.Writable();
writeStream._write = (chunk, encoding, done) => {
console.log(chunk.toString());
done();
};

readStream.pipe(writeStream);

What is Node.js?

Node.js is a JavaScript runtime environment that allows developers to run JavaScript on a server. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js is commonly used for creating web servers, building APIs, and creating real-time applications such as chat applications.

Example:

Let’s say you wanted to create a simple web server using Node.js. You could use the following code:

const http = require(‘http’);

const hostname = ‘127.0.0.1’;
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hello Worldn’);
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});