Site icon DataFlair

NodeJS File System

nodejs file system

FREE Online Courses: Transform Your Career – Enroll for Free!

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

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:

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

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:

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 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

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:

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

3. Read File:

It is used to read files present in your system.

Syntax:

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

Parameter:

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:

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.

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:

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

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

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:

Important node js modules:

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.

Exit mobile version