Create Files in Node.js File System Module


Create Files in Node.js File System
Create Files in Node.js File System

In this tutorial, you will learn how to create files in Node.js file system and it is very simple. There are some built-in methods by which we can do so. So, follow the below methods in a step-by-step process.

  • fs.appendFile()
  • fs.open()
  • fs.writeFile()

fs.appendFile():- This method will help us to create a file and appends some contents inside that file. If the file does not exist, this function will create a new file and adds the specified contents to the created file. If the file exists then this function will add the contents to the file.

Also read, How To Read a file in Node JS

Examples to create files in Node.js file system

Example:- appendfile.js

var fs = require('fs');
fs.appendFile('test2.txt','Hi let me enter',function (err){
	if(err) throw err;
	console.log('saved');
});

Output:- To see the output, open the command terminal in your system and go to the location where the above file is stored, and type the command as shown below

node appendfile.js

fs.open():- This method will help us to create a file to write some contents to that file. This method takes ‘w’ as the second parameter which means it opens the file for writing.

Example:- openfile.js

var fs = require('fs');
fs.open('test3.txt','w',function (err){
	if(err) throw err;
	console.log('saved');
});

Output:- To see the output, open the command terminal and paste the below command

node openfile.js

fs.writeFile():- This function will help us to create a new file with some specific contents. If the file exists then it will replace the contents inside the existing file.

Example:- writefile.js

var fs = require('fs');
fs.writeFile('test4.txt','The name of this file is test4.txt',function (err){
	if(err) throw err;
	console.log('saved');
});

Output:- To see the output, open the command terminal and paste the below command

node writefile.js

Also read, How to Import Custom Module in Node JS

Conclusion:- I hope this tutorial will help you to understand the concept. if there is any doubt then please leave a comment below.


Leave a Comment