- SPLessons

Node.js Interact with File system

Home > > Tutorial
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Node.js Interact with File system

Node.js Interact with File system

shape Introduction

Node.js Interact with File System modules in order to access the physical file system, all the synchronous and asynchronous input/output operations are based on the file system module. Following are the concepts covered.
  • File System (FS) Module.

File System (FS) modules

shape Description

The File System module contains functions which perform operations on files and are implemented by wrapping them around POSIX functions. The file system module functions are accessed using the statement require(‘fs); The table below gives the list of File System methods used in Node.js.
Methods Description
fs.appendFile(file, data[, options], callback) The existing content is added with the new content.
fs.access(path[, mode], callback) The user permissions are tested for a particular file.
fs.exists(path, callback) The method check whether the specified file exist or not.
fs.utimes(path, atime, mtime, callback) The method changes the file timestamp.
fs.readdir(path, callback) The specified directory content can be read by using this method.
fs.mkdir(path[, mode], callback) The method is used to create a new directory.
fs.symlink(destination, path[, type], callback) The method asynchronously symlink.
fs.link(srcpath, dstpath, callback) The file is linked asynchronously using this method.
fs.stat(path, callback) The method returns the object fs.stat including with the important statistics of the file.
fs.chown(path, uid, gid, callback) The method asynchronously chown.
fs.rename(oldPath, newPath, callback) The existing file can be renamed using this method.
fs.open(path, flags[, mode], callback) The method is used to open a file for reading/writing.
fs.writeFile(filename, data[, options], callback) The method creates a new file and write the data into the file, in case if the file exists then overwrite the content.
fs.readFile(fileName [,options], callback) The method is used to read the existing file.
Following are few input and output operations performed using the Node.js File system modules.

Writing a file

shape Description

In order to write the data to a file utilize the function fs.writeFile(filename, data[, options], callback) A new file is created and data is written into the file using the write function or else if the file is created already then the function overwrites the data in that file. The function contain four arguments as follows.

shape Example

The example code below demonstrate creating a file and writing the given data into that file. write.js [c] var fs = require('fs'); fs.writeFile('demo.txt', 'Node.js', function (err) { if (err) console.log(err); else console.log('A file created with the given data.'); }); [/c] Compiling the above code will produce the output as shown in the image below. Now, check the working directory a file demo.txt is created with the given data as shown in the image below. At the same time the content can be added to the existing file content by using the function fs.appendFile() The snippet code below is used to add the content to the above created file i.e. demo.txt. append.js [c] var fs = require('fs'); fs.appendFile('demo.txt', '-Tutorials', function (err) { if (err) console.log(err); else console.log('Extra content is added to the creted file.'); }); [/c] Compiling the above code will produce the output as shown in the image below. Now, check the file  demo.txt in the working directory the data in the file get added with the given content  as shown in the image below.

Read a file

shape Description

In order to read the data from a file utilize the function fs.readFile(fileName [,options], callback) A new file is created and data is written into the file or else if the file is created already then the function overwrites the data in that file. The function contain four arguments as follows. The data from a file can be read using the read function either in a synchronously or asynchronously. The function have three arguments as follows.

shape Example

The example below demonstrate the code for reading the data from an existing file synchronously. sync.js [c] var fs = require('fs'); var data = fs.readFileSync('demo.txt', 'utf8'); console.log(data); [/c] Compiling the above code will produce the output as shown in the image below. The example below demonstrate the code for reading the data from an existing file asynchronously. async.js [c] var fs = require('fs'); fs.readFile('demo.txt', function (err, data) { if (err) throw err; console.log(data); }); [/c] Compiling the above code will produce the output as shown in the image below.

Opening a file

shape Description

A file can be opened and read using the function fs.open(path, flags[, mode], callback) The function have four arguments as follows. The table below gives the list of all the flags used for the read/write operations.
Flags List Description
a The flag opens the file for appending and in case when a file does not exist a new file is created.
ax The flag is similar to flag 'a' but fails if the path exists.
a+ The flag opens the file for reading and appending, in case when a file does not exist a new file is created.
ax+ The flag is similar to flag 'a+' but fails if the path exists.
w The flag opens the file for writing, in case when a file does not exist a new file is created or if exist the file get truncated.
wx The flag is similar to flag 'w' but fails if the path exists.
w+ The flag opens the file for reading and writing, in case when a file does not exist a new file is created or if exist the file get truncated.
wx+ The flag is similar to flag 'wx+' but fails if the path exists.
r The flag opens the file for reading, in case when a file does not exist an exception get occurs.
r+ The flag opens the file for reading and writing, in case when a file does not exist an exception get occurs.
rs The flag opens the file in synchronous mode for reading.
rs+ The flag opens the file for reading and writing and tell the OS to open the file in synchronous mode.

shape Example

The example below demonstrate the code for opening and reading the data from an existing file. open.js [c] var fs = require('fs'); fs.open('demo.txt', 'r', function (err, fd) { if (err) { return console.error(err); } var buffr = new Buffer(1024); fs.read(fd, buffr, 0, buffr.length, 0, function (err, bytes) { if (err) throw err; if (bytes > 0) { console.log(buffr.slice(0, bytes).toString()); } fs.close(fd, function (err) { if (err) throw err; }); }); }); [/c] Compiling the above code will produce the output as shown in the image below.

Deleting a file

shape Description

A file can be deleted using the function fs.unlink(path, callback); The function have tow arguments as follows.

shape Example

The example below demonstrate the code for deleting an existing file. delete.js [c] var fs = require('fs'); fs.unlink('demo.txt', function () { console.log('The file demo.txt is deleted.'); }); [/c] Compiling the above code will produce the output as shown in the image below. The file demo.txt no more exist in the working directory.

Summary

shape Key Points

  • The Node.js included with File system modules in order to access physical file system.
  • The synchronous and asynchronous input/output operations are based on the file system modules.
  • The module functions are wrapped and implemented around the POSIX functions.