Node js
Introduction to Node.js
Node.js is an open-source and cross-platform JavaScript runtime environment. It
is a popular tool for almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the
browser. This allows Node.js to be very performant.
A Node.js app runs in a single process, without creating a new thread for every
request. Node.js provides a set of asynchronous I/O primitives in its standard
library that prevent JavaScript code from blocking and generally, libraries in
Node.js are written using non-blocking paradigms, making blocking behavior the
exception rather than the norm.
When Node.js performs an I/O operation, like reading from the network, accessing
a database or the filesystem, instead of blocking the thread and wasting CPU
cycles waiting, Node.js will resume the operations when the response comes
back.
This allows Node.js to handle thousands of concurrent connections with a single
server without introducing the burden of managing thread concurrency, which
could be a significant source of bugs.
Node.js has a unique advantage because millions of frontend developers that
write JavaScript for the browser are now able to write the server-side code in
addition to the client-side code without the need to learn a completely different
language.
Node js 1
In Node.js the new ECMAScript standards can be used without problems, as you
don't have to wait for all your users to update their browsers - you are in charge of
deciding which ECMAScript version to use by changing the Node.js version, and
you can also enable specific experimental features by running Node.js with flags.
An Example Node.js Application
The most common example Hello World of Node.js is a web server:
CJSMJS
const { createServer } = require("node:http");
const hostname = "127.0.0.1";
const port = 3000;
const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/
`);
});
To run this snippet, save it as a server.js file and run node server.js in your
terminal.
This code first includes the Node.js http module.
Node.js has a fantastic standard library, including first-class support for
networking.
The createServer() method of http creates a new HTTP server and returns it.
The server is set to listen on the specified port and host name. When the server is
ready, the callback function is called, in this case informing us that the server is
running.
Node js 2
Whenever a new request is received, the request event is called, providing two
objects: a request (an http.IncomingMessage object) and a response
(an http.ServerResponse object).
Those 2 objects are essential to handle the HTTP call.
The first provides the request details. In this simple example, this is not used, but
you could access the request headers and request data.
The second is used to return data to the caller.
In this case with:
res.statusCode = 200;
we set the statusCode property to 200, to indicate a successful response.
We set the Content-Type header:
res.setHeader("Content-Type", "text/plain");
and we close the response, adding the content as an argument to end() :
res.end("Hello World\n");
Node.js file stats
Every file comes with a set of details that we can inspect using Node.js. In
particular, using the stat() method provided by the fs module.
The file information is included in the stats variable. What kind of information can
we extract using the stats?
A lot, including:
if the file is a directory or a file, using stats.isFile() and stats.isDirectory()
if the file is a symbolic link using stats.isSymbolicLink()
the file size in bytes using stats.size .
Node js 3
You can also use promise-based fsPromises.stat() method offered by
the fs/promises module if you like:
const fs = require("node:fs/promises");
async function example() {
try {
const stats = await fs.stat("/Users/joe/test.txt");
stats.isFile(); // true
stats.isDirectory(); // false
stats.isSymbolicLink(); // false
stats.size; // 1024000 //= 1MB
} catch (err) {
console.log(err);
}
}
example();
Node.js File Paths
Every file in the system has a path. a path might look like: /users/joe/file.txt while
Windows computers are different, and have a structure such
as: C:\users\joe\file.txt
You need to pay attention when using paths in your applications, as this difference
must be taken into account.
You include this module in your files using const path = require('node:path'); and you
can start using its methods.
Getting information out of a path
Given a path, you can extract information out of it using those methods:
dirname : gets the parent folder of a file
basename : gets the filename part
Node js 4
extname : gets the file extension
const path = require('node:path');
const notes = '/users/joe/notes.txt';
path.dirname(notes); // /users/joe
path.basename(notes); // notes.txt
path.extname(notes); // .txt
You can get the file name without the extension by specifying a second argument
to basename :
path.basename(notes, path.extname(notes)); // notes
Working with paths
You can join two or more parts of a path by using path.join() :
const name = "joe";
path.join("/", "users", name, "notes.txt"); // '/users/joe/no
tes.txt'
You can get the absolute path calculation of a relative path using path.resolve() :
path.resolve("joe.txt"); // '/Users/joe/joe.txt' if run from
my home folder
path.normalize() is another useful function, that will try and calculate the actual
path, when it contains relative specifiers like . or .. , or double slashes:
Node js 5
path.normalize("/users/joe/..//test.txt"); // '/users/test.tx
t'
Neither resolve nor normalize will check if the path exists. They just calculate a
path based on the information they got.
Reading files with Node.js
The simplest way to read a file in Node.js is to use the fs.readFile() method,
passing it the file path, encoding and a callback function that will be called with
the file data (and the error):
You can also use the promise-based fsPromises.readFile() method offered by
the fs/promises module:
const fs = require("fs/promises");
const text = async () => {
try {
const first = await fs.readFile("./content/first.txt", "u
tf8");
const second = await fs.readFile("./content/second.txt",
"utf8");
console.log(first + second);
} catch (error) {
console.log("error");
}
};
text();
All three of fs.readFile() , fs.readFileSync() and fsPromises.readFile() read the full
content of the file in memory before returning the data.
Node js 6
This means that big files are going to have a major impact on your memory
consumption and speed of execution of the program.
In this case, a better option is to read the file content using streams.
Writing files with Node.js
The easiest way to write to files in Node.js is to use the fs.writeFile() API.
You can also use the promise-based fsPromises.writeFile() method offered by
the fs/promises module:
const fs = require("node:fs/promises");
async function example() {
try {
const content = "Some content!";
await fs.writeFile("/Users/joe/test.txt", content);
} catch (err) {
console.log(err);
}
}
example();
By default, this API will replace the contents of the file if it does already exist.
You can modify the default by specifying a flag:
fs.writeFile("/Users/joe/test.txt", content, { flag: "a+" });
Appending content to a file
Appending to files is handy when you don't want to overwrite a file with new
content, but rather add to it.
Here is a fsPromises.appendFile() example:
Node js 7
const fs = require("node:fs/promises");
async function example() {
try {
const content = "Some content!";
await fs.appendFile("/Users/joe/test.txt", content);
} catch (err) {
console.log(err);
}
}
example();
Working with folders in Node.js
The Node.js fs core module provides many handy methods you can use to work
with folders.
Check if a folder exists
Use fs.exists() (and its promise-based fs.existsSync() counterpart) to check if the
folder exists and Node.js can access it with its permissions.
Create a new folder
Use fs.mkdir() or fs.mkdirSync() or fsPromises.mkdir() to create a new folder.
const fs = require("node:fs");
const folderName = "/Users/joe/test";
try {
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
} catch (err) {
Node js 8
console.error(err);
}
Read the content of a directory
Use fs.readdir() or fs.readdirSync() or fsPromises.readdir() to read the contents of a
directory.
This piece of code reads the content of a folder, both files and subfolders, and
returns their relative path:
const fs = require("fs/promises");
const folderPath = "/Users/joe";
const readingdata = async () => {
const first = await fs.readdir(folderPath);
for (const iterator of first) {
// work
}
};
Rename a folder
Use fs.rename() or fs.renameSync() or fsPromises.rename() to rename folder. The first
parameter is the current path, the second the new path:
fsPromises.rename() is the promise-based version:
const fs = require("node:fs/promises");
async function example() {
try {
await fs.rename("/Users/joe", "/Users/roger");
} catch (err) {
console.log(err);
}
}
example();
Node js 9
Remove a folder
Use fs.rmdir() or fs.rmdirSync() or fsPromises.rmdir() to remove a folder.
const fs = require("node:fs");
fs.rmdir(dir, (err) => {
if (err) {
throw err;
}
console.log(`${dir} is deleted!`);
});
To remove a folder that has contents use fs.rm() with the option { recursive: true
} to recursively remove the contents.
{ recursive: true, force: true } makes it so that exceptions will be ignored if the
folder does not exist.
const fs = require("node:fs");
fs.rm(dir, { recursive: true, force: true }, (err) => {
if (err) {
throw err;
}
console.log(`${dir} is deleted!`);
});
Export Module
we can export anything like array , object , function from one file to another .
Example: here we have some variables which we had export .
const john = "John";
const suraj = "suraj";
Node js 10
const susan = "susan";
module.exports = { john, suraj, susan };
Example: here we have a function which we had export .
const sayhi = (e) => {
console.log("hello " + e);
};
module.exports = sayhi;
Now we use both exports into our main file
const name = require("./names");
const func = require("./names-say");
func(name.john);
func(name.suraj);
func("susan");
Node js 11