NodeJS File System

Job-ready Online Courses: Click, Learn, Succeed, Start Now!

Nodejs has a builtin module for the file system. We will be using this to perform various operations on files like creating, updating, renaming, deleting etc. So let’s start!!!

Nodejs Create File:

It has mainly 3 methods as below:

1. Append file

The fs.appendFile() method’s second argument takes the text that we want to append, and then it appends at the end of the file if the given file does not exist then the file will be created.

Syntax:

fs.appendfile(filename,text,callback)

Code for appending text in a file:

var fs=require(‘fs’)
fs.appendFile('DataFlairDemo.txt', 'welcome to DataFlair', function (err) {
if (err) throw err;
console.log('Saved!');
});

Output

nodejs fs append file

2. Open file

The fs.open() method’s second argument is “w” for “writing”, which indicates that the file is opened for writing and if it does not exist then an empty file is created.

Syntax:

fs.open(path, flags[, mode], callback)

Parameter:

  • flags − it indicates how the file is to be opened.
  • mode − sets the mode of the file.
  • callback − it is the callback function, takes arguments (err, fd).
  • path − path of the file.

Code for opening a file:

var fs=require(‘fs’)
fs.open('DataFlairDemo.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

Output

nodejs fs openfile

You can see that a file has been added.

3. WriteFile:

The fs.writeFile() method’s second argument takes the text that we want to write, and then it overrides the content available in the file if the given file does not exist then the file will be created.

Syntax:

fs.writeFile(filename, data[, options], callback)

Parameter:

  • flags − it indicates how the file is to be opened.
  • path − path of the file.
  • data − String that has to be written into the file.
  • options − The third parameter is an object which will hold encoding, mode and flag.

Code for writing in a file:

var fs = require('fs');
fs.writeFile('DataFlairDemo.txt', 'Learn Node.js from DataFlair', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

Output

nodejs fs writefile

Nodejs Update File:

It has mainly 2 methods:

1. fs.appendFile()

The fs.appendFile() method’s second argument takes the text that we want to append, and then it appends at the end of the file, if the given file does not exist then the file will be created.

Syntax:

fs.appendfile(filename,text,callback)

Code for fs.appendFile()

var fs=require(‘fs’)
fs.appendFile('DataFlairDemo.txt', 'welcome to DataFlair', function (err) {
if (err) throw err;
console.log('Saved!');
});

Output

nodejs update file by append file

2. fs.writeFile():

The fs.writeFile() method’s second argument takes the text that we want to write, and then it overrides the content available in the file if the given file does not exist then the file will be created.

Syntax:

fs.writeFile(filename, data[, options], callback)

Parameter:

  • flags − it indicates how the file is to be opened.
  • path − path of the file
  • data − String that has to be written into the file.
    options − The third parameter is an object which will hold encoding, mode and flag

Code for writing in a file:

var fs = require('fs');
fs.writeFile('DataFlairDemo.txt', 'Learn Node.js from DataFlair', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

Output

nodejs fs writefile

3. Read File:

It is used to read files present in your system.

Syntax:

fs.read(fd, buffer, offset, length, position, callback)

Parameter:

  • fd − it is a file descriptor returned by fs.open().
  • buffer − buffer for writing the data.
  • offset − buffer to start writing from.
  • length − specifies the number of bytes to read.
  • position − specifies where to begin reading from in the file.
  • callback − it is the callback function, takes arguments (err, fd)

Code for reading a file:

var fs = require('fs');
fs.readFile('DataFlairDemo.txt', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

Output:

Saved!

4. Delete File:

In order to delete a file we will use fs.unlink()method of the file system.

Syntax:

fs.unlink(path, callback)

Parameter:

  • callback − it is the callback function, takes arguments (err, fd).
  • path − path of the file

Code for deleting a file:

var fs = require('fs');
fs.unlink('DataFlairDemo.txt', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

You can see that the file is no longer visible.

nodejs fs delete

5. Rename File:

If we want to rename a file we will use the fs.rename() method of the file system module.

Syntax

fs.rename(name,newName)

Parameter:

  • Name – current file name
  • newName – new file name

Code for renaming a file:

var fs = require('fs');
fs.rename('DataFlair1.txt', 'DataFlair2.txt', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

Output:

Saved!

6. Close a file:

In order to close a file which was opened we will use the fs.close method of the file system module.

Syntax:

fs.close(fd, callback)

Parameters

  • fd − file descriptor returned by fs.open() method.
  • callback − arguments other than a possible exception are provided to this callback.

Code of closing a file:

var fs = require("fs");
var buf =Buffer.alloc(1024);

console.log("opening file");
fs.open('input.txt', 'r+', function (err, fd) {
if (err) {
return console.error(err);
}
console.log("opened successfully!");
console.log("reading the file");

fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {
if (err) {
console.log(err);
}

if (bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

fs.close(fd, function (err) {
if (err) {
console.log(err);
}
console.log("closed successfully.");
});
});
});

Output:

opening file
opened successfully!
reading the file
Welcome to DataFlair
closed successfully.

7. Truncate file:

Many files contain very long text, in order to see a small portion of that file we will use the truncate method of the file system module.

Syntax

fs.ftruncate(fd, len, callback)

Parameters

  • fd − file descriptor returned by fs.open().
  • len − length of the file after which the file will be truncated.
  • callback − arguments other than a possible exception are provided to this callback.

Code for truncating a file:

var fs = require("fs");
var buf = Buffer.alloc(1024);

console.log("opening file");
fs.open('input.txt', 'r+', function (err, fd) {
if (err) {
return console.error(err);
}
console.log("opened successfully!");
console.log("truncating the file after 10 bytes");

fs.ftruncate(fd, 10, function (err) {
if (err) {
console.log(err);
}
console.log("truncated successfully.");
console.log("reading the same file");

fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {
if (err) {
console.log(err);
}

if (bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

fs.close(fd, function (err) {
if (err) {
console.log(err);
}
console.log("closed successfully.");
});
});
});
});

Output:

opening file
opened successfully!
truncating the file after 10 bytes
truncated successfully.
reading the same file
Welcome to
closed successfully.

Node.js File Information:

fs.stat method is used to get the details about the file. We pass the file path in the fs.stat method of the file system module.

Syntax:

fs.stat(path, callback)

Parameter:

Path: file name including path.
Callback: callback function gets two arguments (err, stats)

Node.js fs.Stats:

stats.isfile()returns true when the file type is a simple file.
stats.isdirectory()returns true when the file type is a directory.
stats.isblockdevice()returns true when the file type is a block device.
stats.ischaracterdevice()returns true when the file type is a character device.
stats.issymboliclink()returns true when the file type is a symbolic link.
stats.isfifo()returns true when the file type is a fifo.
stats.issocket()returns true when the file type is socket.

Flags for read or write operations:

  • r:open for reading a file.
  • r+ opening for reading and writing.
  • rs: open reading in synchronous mode.
  • Rs+:open writing and reading in synchronous mode
  • w: open for writing a file.
  • wx: writing but fails if path exists
  • w+ opening for reading and writing.
  • Wx:similar to w+ but fails if path exists
  • a:open for appending a file.
  • ax:similar to a but fails if path exists
  • a+:open file for reading and appending
  • ax+:similar to ax+ but fails if path exists

Important node js modules:

  • fs.chown(path, uid, gid, callback):Asynchronous chown.
  • fs.link(srcpath, dstpath, callback):Links the given file.
  • fs.symlink(destination, path[, type], callback):Symlink asynchronously.
  • fs.rmdir(path, callback):Rename a directory.
  • fs.mkdir(path[, mode], callback):Create a directory.
  • fs.readdir(path, callback):Read the content from the directory.
  • fs.exists(path, callback):checks if file exists or not.
  • fs.access(path[, mode], callback):Tests a user’s permissions for the
  • specified file

Conclusion:

We have seen the different methods for creating and updating a file, we have also seen how to open a file, read a file, delete a file, and also rename a file.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team is a group of passionate educators and industry experts dedicated to providing high-quality online learning resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With years of experience in the field, the team aims to simplify complex topics and help learners advance their careers. At DataFlair, we believe in empowering students and professionals with the knowledge and skills needed to thrive in today’s fast-paced tech industry. Follow us for Free courses, expert insights, tutorials, and practical tips to boost your learning journey.

Leave a Reply

Your email address will not be published. Required fields are marked *