Create A File Inside A Directory In Node JS - onlyxcodes

Sunday, 20 February 2022

Create A File Inside A Directory In Node JS

Hi coders, This tutorial will show you how to create a file inside a directory in Node JS.


The fs built-in module is available in Node JS. The term fs stands for "file system." The module includes all of the necessary functions for reading, writing, and deleting files on the computer system.


The fs module in Node.js allows you to manipulate files programmatically.


I'll show you how to use the fs module to create, read, update, and delete files inside a directory in this tutorial.


Also, this article covers beneficial codes below:


  • How to create a directory.

  • Check a directory exists or not in your root project folder.

  • Check a file already exists or not inside a directory.

  • Read a file line by line

  • Write a file

  • Create multiple files with the same name inside a directory.

So let's go to the tutorial.


create a file Inside a directory in node js - how to create a file in node js command prompt

Table Content

1. Create Project Root Folder

2. Create a Directory

3. Create a File Inside Directory

4. Read File

5. Update File

6. Rename File

7. Read File Line by Line

8. Check File Exists or Not

9. Check Directory Exists or Not

10. Write a File In NodeJS

11. Create Multiple Files In The Same Directory in NodeJS

12. Delete File


Note: I have written all codes and commands in Visual Studio Code editor.


I'm assuming you have the Visual Studio Code editor installed on your computer.


1. Create Project Root Folder

Create a root folder with any name in your drive where you wish to develop a NodeJS application as the first step.


I created a root folder called NodeJS Practice on my H: drive, and under that folder, I developed this application.


Select your root folder path in Visual Studio Code Editor. Look at the two screenshots I've included below.


Select File - Open Folder


select file - open folder

In your drive location, go to the root folder and select it. Take a look at the images I've chosen below.


select root project directory of your node js application

To create a new file in the root folder, click the folder plus sign icon, give it the name index.js, and press enter. Look at the graphic below.


Within the index.js file, we will write all Node JS codes.


create index.js file inside the root project directory

Look at the below first directory structure.


root project folder directory structure

2. Create a Directory

Now, in this step, we'll create a directory and then a file inside this directory.


Go to top select Terminal - New Terminal


go to top select terminal - new terminal

Look the terminal is (command prompt) open on the bottom side. The terminal shows your root application folder path. 


Now we make a directory.


To create the crud name directory (folder), use the Node JS command below in your terminal.


The mkdir command is used to create a directory within our root project folder.


I made the crud name directory here, but you may use any name you like.


mkdir crud

See the crud folder that was also generated in our project's root directory.


crud directory created inside the root project folder

3. Create a File Inside Directory

We now create a file in the crud directory. Copy and paste the Node JS code below into your index.js file.


const fs = require('fs');

const path = require('path');

const dirPath = path.join(__dirname, 'crud');


//create a file

fs.writeFileSync(dirPath+ "/test.txt", "This is simple file");
console.log("File Created Successfully");

Explanation:


The Node.js file system module enables us to communicate with your computer's file system.


Use the require() function to add the File System module.


The 'fs' module offers a Functionality for working with the File System and performing I/O operations like creating, reading, updating, and deleting files.


The fs module has both synchronous and asynchronous methods.


The Path module allows you to work with file and directory paths.


In Node JS, the path module is a core module. As a result, you don't need to install it to utilize it.


Use the require() function to install the Path module.


Understand below, 


const dirPath = path.join(__dirname, 'crud');

The path.join() method combines the path sections you specify into a single path. The path sections must, however, be strings separated by commas.


The __dirname command returns the directory's absolute path.


Within the path.join() method, which returns the directory name, we supply the __dirname command and crud directory name separated by a comma.


We assign the directory path to the dirPath variable when we've obtained it.


The fs.writeFileSync() is a synchronous method. We create the test.txt file in our crud directory using the fs.writeFileSync() method.


To create a test.txt name file inside the crud directory, run the Node JS command below in your terminal.


node ./index.js

Output:


node ./index.js

File Created Successfullt

See the test.txt name file in our crud directory, which was successfully generated with a simple message.


create a file inside a directory - node js create file if not exists

Look in a new tab, I've opened the test.txt file.


In a new tab, I've opened the test.txt file - fs create file - node js fs - read file

4. Read File

We're now going to read the contents of the test.txt file. Copy and paste the Node JS code below into your index.js file.


const fs = require('fs');

const path = require('path');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/test.txt`;

//read file 

fs.readFile(filePath, 'utf8', (err,item) => {
  console.log(item);
});

In the file creation code, I covered the File system and Path module.


I skip them to explain and I explain new file read codes.


Understand below,


const filePath = `${dirPath}/test.txt`;

Our crud directory path is stored in the dirPath variable. The test.txt file is also located in the crud directory.


This is a ${` `} Template Literals. It is a new feature of ES6. Template Literals use back-ticks (` `) sign rather than the quotes (" ").


Variable substitutions are possible using template literals using the ${ } syntax.


The dirPath variable is transformed with the template literals syntax ${ }, and the value of this template literal is assigned to the filePath variable.


The fs.readFile() method is a built-in method for reading a file.


The require() method is used to load the fs module.


fs.readFile(filePath, 'utf8', (err,item) => {
  console.log(item);
});

As mentioned above codes, the fs.readFile() method accepts three parameters.


filename: It contains the name of a file that has to be read. The filePath variable, which stores the path to the test.txt file, is assigned here.


encoding: It stores the file's encoding. 'utf8' is the default setting.


callback_function: It is a callback function that is invoked once the file has been read. It requires two inputs:


err: If any mistake appeared.


item: The file's contents.


Finally, the contents of the test.txt file are returned.


To see the file content read successfully, run the Node command below at the terminal.


node ./index.js

Output:


node ./index.js

This is simple file

5. Update File

We're going to add new content to our existing test.txt file in this section.


Copy and paste the Node JS code below into your index.js file.


The code below is the same as the read file codes we discussed previously.


But the change is I used fs.appendFile() method to update content in this method.


The fs.appendFile() method adds the content you provide to the end of the file.


In my test.txt file, I append or update my given content.


const fs = require('fs');

const path = require('path');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/test.txt`;

//update file 

fs.appendFile(filePath, `\n This is second line \n This is third line`, (err) => {
  if(!err) console.log("file updated successfully");
});

To see the new content in the file, run the command below in the terminal.


node ./index.js

Output:


node ./index.js

file updated successfully

6. Rename File

In this phase, we are going to rename our existing test.txt file.


The File System module's fs.rename() method allows you to rename a file.


Our/your existing file will be renamed using the code below. I used the name hello.txt.


const fs = require('fs');

const path = require('path');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/test.txt`;

// rename file

fs.rename(filePath, `${dirPath}/hello.txt`,(err)=>{
   if(!err) console.log("File rename successfully");
});

To see the file rename the successful message, use the following command in the terminal.


node ./index.js

Output:


node ./index.js

File rename successfully

7. Read File Line by Line

We'll read the contents of our hello.txt file line by line in this part.


Copy and paste the following NodeJS code into your index.js file.


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;

//read file line by line

const file = readline.createInterface({
    input: fs.createReadStream(filePath),
    output: process.stdout,
    terminal: false
})

file.on('line', (line) => {
    console.log(line);  
})

Explanation:


The majority of the codes in this area are the same as the ones we reviewed in the file creation, read, and update sections.


So I skipped over the old codes and simply covered the new ones here.


Readline is a NodeJS core module that was created to read content line by line from any readable stream.


It's able to read data from the command line with this platform.


The module does not require installation and can be imported because it is a core Node.js module.


To add the Node JS Readline module in the index.js code, create a variable readline and apply the require() method to it.


const readline = require('readline');

Because the readline module only works with Readable streams, we must first use the fs module to build a readable stream.


Our file path is stored in the filePath variable.


The createInterface() creates an Interface object. 


const file = readline.createInterface({
    input: fs.createReadStream(filePath),
    output: process.stdout,
    terminal: false
})

Now, on the file object, look for the line event. When a new line is read from the stream, the event will be activated.


Monitoring for the line event, which is initiated every time a new line is read from the stream, to print the contents of the file line by line to the console.


file.on('line', (line) => {
    console.log(line);  
})

To read the contents of our file, use the command below in the terminal.


node ./index.js

Output:


node ./index.js

This is simple file
 This is second line
 This is third line

8. Check File Exists or Not

In this section, we'll see if the file we're looking for already exists in our crud name directory.


The below Node JS code checks file already exists or not. If not exists then it will return the message of creating a new file in the console.


Our crud directory path is stored in the dirPath variable, and the hello.txt file is located within the crud directory.


The dirPath variable is replaced with the template literals syntax ${ }, and the value of this template literal is allocated to the filePath variable.


We pass the filePath variable to the fs.existsSync() method, which verifies whether or not the file exists in our crud directory.


The fs.existsSync() method is used to verify if a file already exists in the provided path in a synchronous manner. It returns a boolean value that shows whether or not a file exists.


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;

//check file exists or not

if(fs.existsSync(filePath)){
    console.log("Sorry File Already Exists");    
}
else{
    console.log("Create a new file");
}

To see if a file exists or not, run the command below in the terminal.


node ./index.js

Output:


node ./index.js

Sorry File Already Exists

9. Check Directory Exists or Not

We'll verify whether or not a directory exists in our root project directory in this section.


We recently discussed the code of a file exists or not in our crud directory.


The code below is same to the code of a file that already exists.


But, instead of sending the filePath variable to the fs.existsSync() method, we send the dirPath variable. Because the filePath variable has the file name and the dirPath variable holds the current directory path.


If a directory name already exists, the fs.existsSync() method returns the message that the directory already exists, otherwise it returns the message that a new directory should be created in the console.


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;


//check directory exists or not

if(fs.existsSync(dirPath)){
    console.log("Sorry Directory Already Exists");    
}
else{
    console.log("Create a new Directory");
}

To see if a directory exists or not, run the command below in the terminal.


node ./index.js 

Output:


node ./index.js

Sorry Directory Already Exists

10. Write a File In NodeJS

You will see how to write a file in node js in this part.


If the requested file and content already exist, the fs.writeFile() method overwrites them. If the file does not exist, a new one will be created with the supplied content.


The fs.writeFile() method code below adds new content to an existing file.


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;


// fs.writeFile() example
fs.writeFile(dirPath+ '/hello.txt', `This is simple file \n This is second line`, function (err) {
    if (err) throw err;
    console.log('Task done completed');
});

To see the write file successfully message, run the following command in the terminal.


node ./index.js

Output:


node ./index.js

write file successfully

Second Example,


If you give a different file name, the fs.writeFile() method will create and write content to a file inside a directory.


For instance, if I used the file name fruit.txt and ran the following code, the fs.writeFile() method created a fruit.txt file in my directory and wrote a text to it.


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;


fs.writeFile(dirPath+ '/fruit.txt', `This is a apple \n This is mango`, function (err) {
    if (err) throw err;
    console.log('new file write successfully with content');
});

Execute the below command to see the output.


node ./index.js

Output:


node ./index.js

new file write successfully with content

I mentioned the below screenshots. The fruit.txt name file was created in my directory, and I opened it in a new tab to see the written content of the fruit.txt file.


I've opened fruit.txt name file in a new tab - node js write to file line by line - fs.writefile example

11. Create Multiple Files in the Same Directory in NodeJS

In this lesson, you'll learn how to create several files in the same directory.


With the help of the for loop and fs.writeFileSync(), the Node JS code creates 5 files with the same name in the crud directory. 


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;


for(i=0; i<5; i++)
{
    fs.writeFileSync(dirPath+"/test"+i+".txt", "a simple test file");
}

Run the command below in your terminal to create five files.


node ./index.js

Output:


Look above Node JS code created five files inside my crud directory.


the node js code created multiple files with the same name inside crud directory

12. Delete File

This is the last section, and you will learn how to delete a file in node js.


The fs.unlinkSync() method deletes a particular file that you specify.


For example, The Node JS code deleted my hello.txt file using the fs.unlinkSync() method.


const fs = require('fs');

const path = require('path');

const readline = require('readline');

const dirPath = path.join(__dirname, 'crud');

const filePath = `${dirPath}/hello.txt`;


//delete file from the directory

fs.unlinkSync(`${dirPath}/hello.txt`);

To delete the file you supplied, use the command below.


node ./index.js

No comments:

Post a Comment

Post Bottom Ad