Connect with us


Writing Files In Nodejs? Here Is What You Need To Know.



nodejs files

NodeJs file system module will allow us to do file operations create, read, write, update, delete, rename. In this blog, we will use the fs module to perform file operations. In the fs module, every method has asynchronous as well as synchronous forms. Asynchronous methods take the first parameter of the callback function as error and the last parameter as the completion function callback. It’s better to go with the asynchronous method instead of the synchronous method.

Now let’s move on to Nodejs file examples

Step 1: Create a directory for our application.

$ mkdir nodeFileOperations

$ cd nodeFileOperations

Step 2: Now generate package.json. Run the following command. So that all the dependencies can be listed.

$ npm init

sub buzz 1275 1560244682 1


Step 3: Install the fs module by the following command

$ npm install fs

After installing the fs module and make your nodejs server run. It will run on port 3000. Please find below code.

const fs = require(‘fs’);

const bodyParser = require(‘body-parser’);

const session = require(‘express-session’);

const cors = require(‘cors’);

const app = express();



secret : ‘thesecret’,

saveUninitialized: false,

resave : false


router = express.Router({

mergeParams: true

}), router.use(cors());

const startServer = async () => {

const port = process.env.SERVER_PORT || 3000;

await promisify(app.listen).bind(app)(port);

console.log(`Listening on port ${port}`);



module.exports = router;


Important flags:

r: Open file for reading, the exception will come when a file does not exist.

r+: Open file for reading and writing, the exception will come when the file does not exist.

rs: Open file for reading in the mode of synchronous.

rs+: Open file for reading and writing, asking the OS to open the file in the mode of synchronous.

w: Open file for writing. The file will create if not exist or truncate if exist.

wx: Open file for writing like ‘w’ but fails if the path exists.

w+: Open file for reading and writing, the file is created if it does not exist or truncated if exists.

wx+: Open file for read and write like ‘w+’ but fails if the path exists.

a: Open file for appending, the file will create if it does not exists.

ax: Open file for appending like ‘a’ but fails if the path exists.

a+: Open file for reading and appending and the file is created if it does not exist.

ax+: Open file for reading and appending like ‘a+’ but fails if the path exists.


Open a file:

To open a file in asynchronous mode use below syntax., flags[, mode], callback)



Path: This is a string should have a file name along with the path.

Flags: Flags indicate the behavior of the file to be opened. All possible flags are mentioned above.

Mode: It sets the file mode, but only the file was created, it defaults to readable and writable.

Callback: Its a callback function which gets two arguments.

console.log(“Going to open file!”);‘input.txt’, ‘r+’, (err, fd) => {

if (err) {

return console.error(err);


console.log(“File opened successfully!..”);



Going to open file

Listening on port 3000

File opened successfully!…


Create Files:

To create new files fs module has the following methods:



The fs.appendFile() method appends specific content to the file. If the file does not exist, then the file will create.

const fs = require(‘fs’);

fs.appendFile(‘input.txt’, ‘Hello content!’, (err) => {

if (err) throw err;

console.log(‘Content Saved!..’);



Listening on port 3000

console.log(‘Content Saved!..’);

fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file containing the given content will be created.

const fs = require(‘fs’);

fs.writeFile(‘input.txt’, ‘Hello Write file content!’, (err) => {

if (err) throw err;

console.log(‘Write file content saved!…’);



Listening on port 3000

Write file content saved!…


Update Files:

The fs module has the following methods for updating.

fs.appendFile(): This method appends the given content at the end of the specified file.

fs.writeFile(): This method replaces the given file and content.


Delete Files:

fs.unlink() method will use to delete a file by using fs module.

const fs = require(‘fs’);

fs.unlink(‘input.txt’, (err) => {

if (err) throw err;

console.log(‘File deleted!..’);



Listening on port 3000

File deleted!…


Rename Files:

fs.rename() method will be used to rename a specified file.

const fs = require(‘fs’);

fs.rename(‘input.txt’, ‘input_renamed.txt’ (err) => {

if (err) throw err;

console.log(‘File Renamed!..’);



Create a Directory:

fs.mkdir() method is used to make a directory:

const fs = require(‘fs’);

fs.mkdir(‘/tmp/home/test’, (err) => {

if (err) throw err;

console.log(“Directory created successfully!..”);



Listening port 3000

Directory created successfully!…


Read a Directory:

fs.readdir() method is used to read a directory.

const fs = require(‘fs’);

fs.readdir(“/tmp/home/nodeFileOperations/”, (err, files) => {

if (err) throw err;

files.forEach((file) => {





Listening on port 3000








Remove a Directory:

fs.rmdir() method is used to remove a directory

const fs = require(‘fs’);

fs.rmdir(“/tmp/home/nodeFileOperations/”, (err) => {

if (err) throw err;

console.log(“Going to read directory /tmp/home/”);

fs.readdir(“/tmp/home/”, (err, files) => {

if (err) throw err;

files.forEach((file) => {






Useful methods of fs module:

fs.readFile(file_name [,options], callback): This method reads an existing file.

fs.writeFile(file_name, data[, options], callback): This method writes to the file. If a file exists then overwrite the content otherwise it will create a new file., flags[, mode], callback): This method open file for reading or writing.

fs.rename(oldPath, newPath, callback): This method will rename an existing file.

fs.chown(path, uid, gid, callback): This will asynchronous chown.

fs.stat(path, callback): This method will return fs.stat object which includes important file statistics., dstpath, callback): This method will links a file asynchronously.

fs.symlink(destination, path[, type], callback): This method will do Symlink asynchronously.

fs.rmdir(path, callback): This method will rename an existing directory.

fs.mkdir(path[, mode], callback): This method will create a new directory.

fs.readdir(path, callback): This method will read the content of the specified directory.

fs.utimes(path, atime, mtime, callback): This method changes the timestamp of the file.

fs.exists(path, callback): This method determines whether the specified file exists or not.

fs.access(path[, mode], callback): This method will test a user’s permissions for the specified file.

We are top React.js development company developing with cutting edge technology and tools to solve everyday problems and bring endless enjoyment in the form of a robust application. Established by a team of accomplished tech entrepreneurs, we are proud to develop, program and deliver top tier mobile applications with integrity and perfectionism.