Node.js installs the fs module to access the physical file system. Module fs handles all asynchronous I/O performance or synchronization.

Let's look at some of the most common examples of I / O performance using the fs module.

Reading File

Use the fs.readFile () method to read the visual file voluntarily.

fs.readFile(file_name [,options], callback)

Parameter Description:

filename: Full path and name of the file as a string.

options: The options parameter can be an object or string which can include encoding and flag. The default encoding is utf8 and default flag is "r".

callback: A function with two parameters err and fd. This will get called when readFile operation completes.

The below example demonstrates reading existing TestFile.txt asynchronously.

Example

var fs = require('fs');

fs.readFile('TestFile.txt', function (err, data) {
                    if (err) throw err;

    console.log(data);
});

The example above reads TestFile.txt in sync and runs the callback function when the reading task is complete. This reading task is misleading or successful. The err parameter contains error details if available. The data parameter contains the specified file contents.

The below is a sample TextFile.txt file.

Example

This is test file to test fs module of Node.js

Now, run the above example and see the result as shown following.

C:\> node server.js
This is test file to test fs module of Node.js

Use fs.readFileSync() method to read file synchronously as shown below.

Example

var fs = require('fs');

var data = fs.readFileSync('dummyfile.txt', 'utf8');
console.log(data);

Writing File

Use fs.writeFile () method to write data to a file. If the file already exists it overwrites existing content otherwise creates a new file and writes data to it.

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

Example

var fs = require('fs');

fs.writeFile('test.txt', 'Hello World!', function (err) { 
                        if (err)
        console.log(err);
                        else
        console.log('Write operation complete.');
});

Open File

Also, you can open a file for reading or writing using fs.open() method.

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

Delete File

Use fs.unlink() method to delete an existing file.

fs.unlink(path, callback);

The below example deletes an existing file.

Example

var fs = require('fs');

fs.unlink('test.txt', function () {
    
    console.log('write operation complete.');

});