Nodejs Notes
Nodejs Notes
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.
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.
To run this snippet, save it as a server.js file and run node server.js in your
terminal.
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.
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World\n");
The file information is included in the stats variable. What kind of information can
we extract using the stats?
A lot, including:
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();
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.
Node js 4
extname : gets the file extension
You can get the file name without the extension by specifying a second argument
to basename :
You can get the absolute path calculation of a relative path using path.resolve() :
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.
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();
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.
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:
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();
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);
}
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
{ 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 .
Node js 10
const susan = "susan";
module.exports = { john, suraj, susan };
Node js 11