DEV Community

Cover image for Write a file into specific folder in Node JS example
biplab3
biplab3

Posted on

Write a file into specific folder in Node JS example

Hi friends, in this tutorial you will learn how to write a file into specific folder in node js and it is a very basic concept of a node js filesystem. In order to write a file you have to follow the below steps:

Required steps to write a file into specific folder in Node JS

Step 1:- Create a folder inside the node js application or anywhere you want.

Step 2:- Create a file with a .js extension inside the node js application. For eg:- filesystem.js

Also read, Node Js hello world program

Now, before writing a file, you have to include two built-in modules of node js as given below

fs module:- In order to work with the filesystem such as creating a file, reading a file, updating the file, and deleting a file in node js, there is a built-in module called "fs". You can use this module with the help of require() method as shown below.

const fs = require("fs");

path module:- In order to get the path of a specific folder of the directory, you can include this module as shown below.

const path = require("path");

Step 3:- In the filesystem.js file, call the above two modules as given below.

const fs = require('fs');
const path = require('path');

Step 4:- Now, get the path of the specific folder where you want to write the file using the path variable with the help of the join() method as shown below.

const directory = path.join(__dirname,'your folder name');

Now, if you console the above directory variable and run your node js file in the terminal then you can see the folder path as shown below

D:\nodejs_tutorials\myfiles

Step 5:- Next, we will create the file using the writeFileSync() function with the help of filesystem constant "fs". as given below.

fs.writeFileSync(directory+"/test.txt","Hi this is a text file");

Note that in the above line of code, do not forget to include the directory inside the writeFileSync() function because the file will be created inside that specific directory.

Also, read, How to install package JSON file in node js

Step 6:- Now, in the VS code, open the terminal and run the node js file (filesystem.js) and you will see that the test.txt file has been created under the specific folder you mentioned at the time of directory declaration.

Complete Code:- (filesystem.js)

const fs = require('fs');
const path = require('path');
const directory = path.join(__dirname,'myfiles');
//console.log(directory);
fs.writeFileSync(directory+"/test.txt","Hi this is a text file");
Enter fullscreen mode Exit fullscreen mode

Conclusion:- I hope this tutorial will help you to understand the concept.

Top comments (0)