To create a file using CMD in the Node JS
both type and echo can create a file and for creating an empty file
“ > ”is a redirection operation It is used to redirect the output of one command to another command or file.
type nul > index.js
// or
echo index.js
And for adding content to new or existing files by using type or echo
echo something file.txt
and if we want to put some content to another file using CMD
type file.txt > index.js
And for both of them appending the content instead of overriding we use >> for >
echo some_text >> file.txt
And to know what exactly Node js is then go to this article
Earlier in JavaScript we had the limitation that we could only write scripts in a browser because of the v8 JavaScript engine but now we can directly write in our in-node Js environment that is nothing but REPL (Read, Eval, Print & Loop)
- Using variable

2. Multiline code or loop
By using template literals we can combine both string and variable by using backtick

3. Use “ _ “ to get the last data in node js
Now what is the requirement of “ _ ” we use the underscore symbol to get the last data. Let’s suppose we are continuously adding the two numbers initially will take any two random numbers and will go with result + any number but when adding let’s say we do not know the result and we just add. So at that particular time, we use the underscore symbol.
3 + 4
>> 7
7 + 8 // we using the result here is 7
>> 15
_ + 5 // Here I don't know the previous result so I just use "_"
>> 20

4. Editor mode
To go into editor mode open your current directory enter node and then .editor
Node Js Core Modules
Node js has an ample of core modules that come preinstalled in a runtime of node js. These modules provide the functionalities for the building of real-world application
fs module
By using this module we can read and write files in our terminal and use this file system. Initially, we need to require it to move further.
require(“fs”) // we just required it but we need to store it somewhere
const path = require('path');
// Now we will write into a file
// creating a new file although if it exists already then it will override
fs.writeFileSync('read.txt', 'I am Groot');
Synchronization means let’s say, in the context of a restaurant, efficiently managing customer orders. For instance, when two customers arrive simultaneously at a hotel, we first take the order of the initial customer. After transmitting the order to the kitchen, we await the completion of dish preparation by the cook. Once ready, we serve the first customer. While this process may seem time-consuming, it ensures a sequential flow. In a synchronized workflow, we refrain from taking the order of the second customer until the first order is served, maintaining a systematic and organized service.
Ok as we are curious to know what is inside the file. So we tend to read the data from the file
Node Js includes an additional data type called buffer which is not available in the browser’s JavaScript buffer is mainly used to store binary data when reading from the file or receiving packets over the network
So whenever we try to read the file we get this buffer data but we need to convert it into a normal string so that we can understand it easily. For converting buffer to string we use a method provided by buffers called toString(). This method takes two argument encoding and optional position. The first argument specifies the format in which we want to convert the buffer to a string. In our case, we pass ‘utf8’ as the encoding which represents the Unicode UTF-8 character
Here is the complete code:
// Here is the complete code:
const buffer_data = fs.readFileSync('read.txt');
console.log(buffer_data);
// <Buffer 49 20 61 6d 20 67 72 6f 6f 74>
original_data = buffer_data.toString();
console.log(original_data);
//I am Groot
To rename the file
first, we write the file name and the name that we want to update
// Here is the code:
fs.renameSync('read.txt', 'readWrite.txt');
// reading the updated file
updated_file_content = fs.readFileSync('readWrite.txt');
console.log(updated_file_content);
// check if file exists or not
if(fs.existsSync('readWrite.txt')){
console.log("The file is present in directory ");
}else{
console.log("The file is not present in directory ");
}
let dataToAppend='This is some more data adding in the file';
// append data to the end of the file
fs.appendFileSync('readWrite.txt', '\n' + dataToAppend);
Solving challenges CRUD Operations using FS Module in NodeJS
Synchronous version
create -> writeFileSync()
read -> readFileSync(), fs.read()
update/rename -> renameSync(), appendFileSync()
delete -> unlinkSync()
Asynchronous version for all above methods
create -> writeFile(), readFile()
read -> readFile()
update/rename -> rename(), appendFile()
delete -> unlink()
Create — When we add something into our database like inserting a record in the table. So we will create a new folder
// To create a new folder using cmd in node js
const fs = require('fs');
fs.mkdirSync("Om");
now we will create a new file in that folder, If a new file already exists in the folder then it will override the data else it will create a new file and add the data accordingly.
Read — When we retrieve information from our database like fetching records from table
const data1 = fs.readFileSync('Om/newfile.txt');
console.log(data1);
const data = fs.readFileSync('Om/newfile.txt', 'utf-8');
console.log(data);
Update — When we modify existing information in our database like updating records in table
fs.renameSync('Om/newfile.txt','Om/updatedfile.txt');
Delete — When we remove information from our database like deleting records from table
// to delete the file
// fs.writeFileSync('Om/Data.txt',"new data");
fs.unlinkSync("Om/Data.txt");
// to delete the folder
fs.rmdirSync('Om/updatedfile.txt');
Asynchronous File System Core Modules
what is a callback?
A callback function in Node.js is a function that is passed as an argument to another function and executed or called back at some point in the future when the operation being waited on is completed.
To create a file
const fs = require('fs');
fs.writeFile('read.txt','today is awesome day',(err)=>{
console.log("data written");
console.log(err);
});
To append/update the data
fs.appendFile('read.txt',"\nI am adding data statement", (err)=>{
if(!err){
console.log("Data is appended in the file");
}else{
console.log("Data is not appended in the file", err);
}
});
To read the data
fs.readFile('read.txt', 'utf8', (err, data) => {
if (err) throw err;
//console log will print after the execution of all lines of code
console.log(`${data}`);
// process the data here
});
fs.readFile('read.txt','utf-8', (err,data)=>{
if(err) throw err;
else
console.log("The content of the file is : "+data.toString());
});
utf-8 is a file encoding so that we don’t get any buffer data.
Synchronous vs Asynchronous in NODE JS
Synchronous code:
const data = fs.readFileSync('read.txt', 'utf-8');
console.log(data);
console.log("After the data");
// In sync it won't move to next until and unless it completes the process
// of current data.
// First it will print the data then move to next
Asynchronous code
const data = fs.readFile('read.txt', "utf-8", (err,data)=>{
console.log(data);
});
console.log("After the data");
// In async if it takes more time then it won't wait it moves next and print
// In this first print "After the data" then the data in the read.txt file
Asynchronous CRUD Operations using File System Modules in NodeJS
To Create a folder by asynchronous method
const fs = require('fs');
const path = require('path');
fs.mkdir('Om',(err)=>{
if(err){
console.log(err);
}
console.log("Folder created");
});
Now we can create a file inside the Om folder
// To write a file
fs.writeFile('Om/mydata.txt',"My name is Omprakash",(err)=>{
console.log("File created");
});
To append the data to the existing file
// To append the data
fs.appendFile("Om/mydata.txt",'\nAppending the new data',(err)=>{
console.log("Data appended");
});
To read the file
// To read the file without getting the buffer data, async
fs.readFile('Om/mydata.txt', "utf-8", (err,data)=>{
if(err){
console.log(err);
}else{
console.log(data);
}
});
To rename the file
// To rename the file
fs.rename('Om/mydata.txt','Om/newfile.txt',(err) => { //Rename the file
if(err) throw err;
console.log('The file has been renamed!');
});
To delete the file
// To delete the file
fs.unlink('Om/newfile.txt', function(err){
if(err) throw err;
console.log('File deleted!');
});
// or
fs.unlink('Om/file.txt',(err)=>{
if(err){
console.log(err);
}else{
console.log("File deleted");
}
});
To delete the folder
// To delete the folder
fs.rmdir('Om', function(err){
if(err){
console.error(err);
} else {
console.log("Directory removed!");
}
});
Node.JS OS Module To Get Operating System Info
Previously we have learned about file systems to perform the CURD operation both synchronous and asynchronous. But now we will learn about the OS module in Node Js. Getting information about the hardware resources of the computer, such as the number of processors, the amount of memory, the type of network interface, the currently logged-in user, all open files on the system
The reason for using the os module in node js is to interact with the operating system as I have mentioned above.
1 byte = 8 bit
1 kilobyte (kb) = 1024 bytes (B)
1 megabyte (MB) = 1024 kb = 1024 * 1024 B = 1048576 Bytes
1 gigabyte (GB) = 1024 MB = 1024 * 1024 * 1024 B = 1073741824 Bytes
1 terabyte (TB) = 1024 GB = 1024 * 1024 * 1024 * 1024 B = 1099511627776 Bytes
const os = require('os');
console.log("os arch : "+os.arch());
const freeMemory = os.freemem();
console.log(`Free memory: ${freeMemory/1024/1024/1024}`);
console.log("homedir : "+os.homedir());
// Returns the home directory of the current user
console.log("Hostname : "+os.hostname());
// Returns the hostname
const totalMem = os.totalmem();
console.log(`Total memory: ${totalMem} Bytes`);
console.log("Number of CPU cores: " + os.cpus().length);
console.log(`Total memory: ${totalMem} Bytes`);
const usedMem = totalMem - freeMemory;
console.log(`Used memory: ${usedMem} Bytes`);
console.log("Total mem : "+totalMem/1024/1024/1024);
console.log("Platform : "+os.platform());
console.log("Os type : "+ os.type());
PATH Module In Node.JS
The path module provides utilities for working with file and directory paths.
const path = require('path');
const fs = require('fs');
console.log(path.dirname('E:/Engineer/Skills required'));
// Prints: E:\Engineer\Skills required
console.log(path.basename('/foo/bar/baz.js', '.js'));
// prints: bar/baz
console.log(path.extname('index.html'));
// prints: .html
console.log(path.join(__dirname, 'secret-folder'));
// prints: D:\NodeJS_Projects\03-FileSystem\12-PathModule\secret-folder
const mypath = (path.parse('E:/Engineer/Skills required'));
console.log(mypath.name);
// prints : Skills required
How to CREATE and EXPORT Our Own Modules in Node JS
what is object destructuring javascript?
Object destructuring in JavaScript is a convenient way to extract properties from objects. It allows you to unpack values from arrays or objects into distinct variables
const person = {
name: 'Omprakash',
age: 22,
city: 'Prakasam'
};
// Destructuring the person object
const {name,age,city} = person;
console.log(name);
console.log(age);
console.log(city);
In Node JS every individual file is a module and whatever code you have written it’s private, Let’s say we have a file called index.js and operator.js and in both files code is private but if we want to access any particular module(index.js or operator.js) we need to export it (module.exports = funName).
// ====== This is index.js file ========
// const add = require('./operator);
// const getName = require('./operator);
const operator = require('./operator');
console.log(operator.add(3,4));
console.log(operator.sub(5,89));
console.log(operator.name);
// console.log(operator.getName);
// const person = {
// name : 'omprakash',
// age: 22,
// city : 'Prakasam'
// };
// // Destructuring the person object
// const {name,age,city} = person;
// console.log(name);
// console.log(age);
// console.log(city);
// Here we are using object destructuring
const {add,sub,name} = require('./operator');
console.log(add(54,6));
console.log(sub(54,6));
console.log(name);
// ======= This is the operator.js file =======
const add = (a,b)=>{
return a+b;
};
const sub = (a,b)=>{
return a-b;
}
const name = "omprakash";
module.exports.add = add;
module.exports.sub = sub;
module.exports.name = name;
Here we can write any name of the function that will be exported in a module.exports but after equal to (=) sign we should mention the actual function which we want to export. This is how we export the function from our module. E.g: module.exports.subtract = sub;
In operator.js if we have observed we repeatedly write module.exports every time for every property, To avoid repetition simply write module.export = {property1, property2, property3};
In object destructuring, we export data or property in any order as an argument and accept the parameter in any order but the name should be the same as every property name. In react we can only accept the parameter if it is in the same order according to the order of argument we have passed.
// Here we are using object destructuring
// Index.js importing properties
const {mul,add,sub,name} = require('./operator'); // accepting parameter
console.log(`Multiplication : ${mul(54,6)}`);
console.log(`Subtraction : ${sub(54,6)}`);
console.log(`Addition : ${add(54,6)}`);
console.log(`My name : ${name}`);
console.log(name);
//-----------------------------------------------------------------------
// operator.js exporting properties
module.exports = {add, sub, name, mul}; // passing argument
Working with expressjs
mkdir expressweb
cd expressweb
mkdir src
typ nul > app.js
cd..
npm init -> To get the node modules and .json files which contains the dependencies
npm install express
In the end for express js only need is a public folder and then with in second it will render the index.html file