Node.js File System
Node.js provides a set of UNIX (POSIX) standard-like file operation APIs. The syntax for importing the file system module (fs) in Node is as follows:
var fs = require("fs")
Asynchronous and Synchronous
The Node.js file system (fs module) methods have both asynchronous and synchronous versions, such as the asynchronous fs.readFile() and the synchronous fs.readFileSync() for reading file content.
The asynchronous method's last parameter is a callback function, and the first parameter of the callback function contains the error information (error).
It is recommended to use asynchronous methods, as they are more performant, faster, and do not block compared to synchronous methods.
Example
Create an input.txt file with the following content:
tutorialpro.org official website: www.tutorialpro.org
File read example
Create a file.js file with the following code:
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program execution complete.");
The above code execution results are as follows:
$ node file.js
Synchronous read: tutorialpro.org official website: www.tutorialpro.org
File read example
Program execution complete.
Asynchronous read: tutorialpro.org official website: www.tutorialpro.org
File read example
Next, let's delve into the methods of the Node.js file system.
Opening a File
Syntax
The following is the syntax for opening a file in asynchronous mode:
fs.open(path, flags[, mode], callback)
Parameters
Parameters are used as follows:
- path - The path of the file.
- flags - The behavior for opening the file. Detailed values are listed below.
- mode - Sets the file mode (permissions), with default creation permissions being 0666 (readable, writable).
- callback - The callback function, with two parameters such as: callback(err, fd).
The flags parameter can be the following values:
Flag | Description |
---|---|
r | Open file for reading. An exception occurs if the file does not exist. |
r+ | Open file for reading and writing. An exception occurs if the file does not exist. |
rs | Open file for reading in synchronous mode. |
rs+ | Open file for reading and writing in synchronous mode. |
w | Open file for writing. The file is created if it does not exist. |
wx | Similar to 'w' but writing fails if the file path exists. |
w+ | Open file for reading and writing. The file is created if it does not exist. |
wx+ | Similar to 'w+' but reading and writing fail if the file path exists. |
a | Open file for appending. The file is created if it does not exist. |
ax | Similar to 'a' but appending fails if the file path exists. |
a+ | Open file for reading and appending. The file is created if it does not exist. |
ax+ | Similar to 'a+' but reading and appending fail if the file path exists. |
Example
Next, we create a file.js file and open the input.txt file for reading and writing. The code is as follows:
var fs = require("fs");
// Asynchronous file open
console.log("Preparing to open the file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
});
The above code execution results are as follows:
$ node file.js
Preparing to open the file!
File opened successfully!
Getting File Information
Syntax
The following is the syntax for getting file information in asynchronous mode:
fs.stat(path, callback)
Parameters
Parameters are used as follows:
- path - The file path.
- callback - The callback function, with two parameters such as: (err, stats), where stats is an fs.Stats object.
After executing
fs.stat(path)
, an instance of thestats
class is returned to its callback function. You can determine the file's attributes using the methods provided by thestats
class. For example, to check if it is a file:var fs = require('fs'); fs.stat('/Users/liuht/code/itbilu/demo/fs.js', function (err, stats) { console.log(stats.isFile()); //true })
The methods in the stats
class include:
Method | Description |
---|---|
stats.isFile() | Returns true if it is a file, otherwise false. |
stats.isDirectory() | Returns true if it is a directory, otherwise false. |
stats.isBlockDevice() | Returns true if it is a block device, otherwise false. |
stats.isCharacterDevice() | Returns true if it is a character device, otherwise false. |
stats.isSymbolicLink() | Returns true if it is a symbolic link, otherwise false. |
stats.isFIFO() | Returns true if it is a FIFO, otherwise false. FIFO is a special type of command pipe in UNIX. |
stats.isSocket() | Returns true if it is a socket, otherwise false. |
Example
Next, we create a file.js
file with the following code:
var fs = require("fs");
console.log("Preparing to open the file!");
fs.stat('input.txt', function (err, stats) {
if (err) {
return console.error(err);
}
console.log(stats);
console.log("File information read successfully!");
// Check file type
console.log("Is it a file (isFile)? " + stats.isFile());
console.log("Is it a directory (isDirectory)? " + stats.isDirectory());
});
The output of the above code is as follows:
$ node file.js
Preparing to open the file!
{ dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 40333161,
size: 61,
blocks: 8,
atime: Mon Sep 07 2015 17:43:55 GMT+0800 (CST),
mtime: Mon Sep 07 2015 17:22:35 GMT+0800 (CST),
ctime: Mon Sep 07 2015 17:22:35 GMT+0800 (CST) }
File information read successfully!
Is it a file (isFile)? true
Is it a directory (isDirectory)? false
Writing to a File
Syntax
The syntax for writing to a file in asynchronous mode is as follows:
fs.writeFile(file, data[, options], callback)
writeFile
opens the file by default in w
mode, so if the file exists, the content written by this method will overwrite the old file content.
Parameters
The parameters are described as follows:
- file - File name or file descriptor.
- data - The data to be written to the file, which can be a String or a Buffer object.
- options - This parameter is an object containing {encoding, mode, flag}. The default encoding is utf8, the mode is 0666, and the flag is 'w'.
- callback - The callback function, which only includes the error parameter (err) and is returned when the write operation fails.
Example
Next, we create a file.js
file with the following code:
var fs = require("fs");
console.log("Preparing to write to the file");
fs.writeFile('input.txt', 'This is the content written to the file by fs.writeFile', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
});
console.log("--------I am the divider line-------------");
console.log("Reading written data!");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read of file data: " + data.toString());
});
The above code execution results are as follows:
$ node file.js
Preparing to write to the file
Data written successfully!
--------I am the divider line-------------
Reading written data!
Asynchronous read of file data: This is the content written to the file via fs.writeFile
Reading a File
Syntax
The following is the syntax for reading a file in asynchronous mode:
fs.read(fd, buffer, offset, length, position, callback)
This method uses a file descriptor to read the file.
Parameters
The parameters are described as follows:
- fd - The file descriptor returned by the fs.open() method.
- buffer - The buffer where the data will be written.
- offset - The offset in the buffer to start writing at.
- length - The number of bytes to read from the file.
- position - The position in the file to start reading from. If the value of position is null, data will be read from the current file position.
- callback - The callback function, with three arguments: err, bytesRead, buffer. err is the error information, bytesRead indicates the number of bytes read, and buffer is the buffer object.
Example
The content of the input.txt file is:
tutorialpro.org official website address: www.tutorialpro.org
Next, we create the file.js file with the following code:
var fs = require("fs");
var buf = new Buffer.alloc(1024);
console.log("Preparing to open an existing file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Preparing to read the file:");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
if (err){
console.log(err);
}
console.log(bytes + " bytes read");
// Output only the bytes read
if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
});
The execution result of the above code is as follows:
$ node file.js
Preparing to open an existing file!
File opened successfully!
Preparing to read the file:
42 bytes read
tutorialpro.org official website address: www.tutorialpro.org
Closing a File
Syntax
The following is the syntax for closing a file in asynchronous mode:
fs.close(fd, callback)
This method uses a file descriptor to close the file.
Parameters
The parameters are described as follows:
- fd - The file descriptor returned by the fs.open() method.
- callback - The callback function, with no parameters.
Example
The content of the input.txt file is:
tutorialpro.org official website address: www.tutorialpro.org
Next, we create the file.js file with the following code:
var fs = require("fs");
var buf = new Buffer.alloc(1024);
console.log("Preparing to open the file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Preparing to read the file!");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
if (err){
console.log(err);
}
console.log(bytes + " bytes read");
// Output only the bytes read
if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
});
The execution result of the above code is as follows:
$ node file.js
Preparing to open the file!
File opened successfully!
Preparing to read the file!
42 bytes read
tutorialpro.org official website address: www.tutorialpro.org
console.log(err);
}
// Only output the bytes read
if (bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}
// Close the file
fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully");
});
});
});
The above code execution results are as follows:
$ node file.js
Ready to open file!
File opened successfully!
Ready to read file!
tutorialpro.org website address: www.tutorialpro.org
File closed successfully
Truncate File
Syntax
The syntax for truncating a file in asynchronous mode is as follows:
fs.ftruncate(fd, len, callback)
This method uses a file descriptor to read the file.
Parameters
The parameters are described as follows:
-
fd - The file descriptor returned by the fs.open() method.
-
len - The length to which the file content is truncated.
-
callback - The callback function, with no parameters.
Example
The content of the input.txt file is:
site:www.tutorialpro.org
Next, we create the file.js file with the following code:
var fs = require("fs");
var buf = new Buffer.alloc(1024);
console.log("Ready to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Truncating file content to 10 bytes, excess content will be removed.");
// Truncate file
fs.ftruncate(fd, 10, function(err) {
if (err) {
console.log(err);
}
console.log("File truncated successfully.");
console.log("Reading the same file");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
if (err) {
console.log(err);
}
// Only output the bytes read
if (bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}
// Close the file
fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully!");
});
});
});
});
The execution result of the above code is as follows:
$ node file.js
Ready to open file!
File opened successfully!
Truncating file content to 10 bytes, excess content will be removed.
File truncated successfully.
Reading the same file
site:www.r
File closed successfully
Delete File
Syntax
The syntax for deleting a file is as follows:
fs.unlink(path, callback)
Parameters
The parameters are described as follows:
-
path - The file path.
-
callback - The callback function, with no parameters.
Example
The content of the input.txt file is:
site:www.tutorialpro.org
Next, we create the file.js file with the following code:
var fs = require("fs");
console.log("Ready to delete file!");
fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});
The execution result of the above code is as follows:
$ node file.js
Ready to delete file!
File deleted successfully!
When I checked the input.txt file again, I found that it no longer existed.
Create Directory
Syntax
The syntax for creating a directory is as follows:
fs.mkdir(path[, options], callback)
Parameters
The parameters are described as follows:
path - The file path.
options parameter can be:
- recursive - Whether to create directories recursively, default is false.
- mode - Sets the directory permissions, default is 0777.
callback - The callback function, which has no parameters.
Example
Next, we create a file.js file with the following code:
var fs = require("fs");
// The tmp directory must exist
console.log("Creating directory /tmp/test/");
fs.mkdir("/tmp/test/", function(err){
if (err) {
return console.error(err);
}
console.log("Directory created successfully.");
});
The result of executing the above code is as follows:
$ node file.js
Creating directory /tmp/test/
Directory created successfully.
You can add the recursive: true
parameter to create the directory /tmp and /tmp/a regardless of whether they exist:
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
Read Directory
Syntax
The syntax for reading a directory is as follows:
fs.readdir(path, callback)
Parameters
The parameters are described as follows:
path - The file path.
callback - The callback function, which takes two parameters: err (error message) and files (an array list of files in the directory).
Example
Next, we create a file.js file with the following code:
var fs = require("fs");
console.log("Viewing /tmp directory");
fs.readdir("/tmp/", function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
The result of executing the above code is as follows:
$ node file.js
Viewing /tmp directory
input.out
output.out
test
test.txt
Remove Directory
Syntax
The syntax for removing a directory is as follows:
fs.rmdir(path, callback)
Parameters
The parameters are described as follows:
path - The file path.
callback - The callback function, which has no parameters.
Example
Next, we create a file.js file with the following code:
var fs = require("fs");
// A empty /tmp/test directory must be created before execution
console.log("Preparing to remove directory /tmp/test");
fs.rmdir("/tmp/test", function(err){
if (err) {
return console.error(err);
}
console.log("Reading /tmp directory");
fs.readdir("/tmp/", function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
});
The result of executing the above code is as follows:
$ node file.js
Preparing to remove directory /tmp/test
Reading /tmp directory
……
File Module Methods Reference Manual
The following is a list of methods in the Node.js file module:
No. | Method & Description |
---|---|
1 | fs.rename(oldPath, newPath, callback) <br>Asynchronous rename(). The callback function has no parameters but may throw an exception. |
2 | fs.ftruncate(fd, len, callback) <br>Asynchronous ftruncate(). The callback function has no parameters but may throw an exception. |
3 | fs.ftruncateSync(fd, len) <br>Synchronous ftruncate() |
4 | fs.truncate(path, len, callback) <br>Asynchronous truncate(). The callback function has no arguments but may throw an exception. |
5 | fs.truncateSync(path, len) <br>Synchronous truncate() |
6 | fs.chown(path, uid, gid, callback) <br>Asynchronous chown(). The callback function has no arguments but may throw an exception. |
7 | fs.chownSync(path, uid, gid) <br>Synchronous chown() |
8 | fs.fchown(fd, uid, gid, callback) <br>Asynchronous fchown(). The callback function has no arguments but may throw an exception. |
9 | fs.fchownSync(fd, uid, gid) <br>Synchronous fchown() |
10 | fs.lchown(path, uid, gid, callback) <br>Asynchronous lchown(). The callback function has no arguments but may throw an exception. |
11 | fs.lchownSync(path, uid, gid) <br>Synchronous lchown() |
12 | fs.chmod(path, mode, callback) <br>Asynchronous chmod(). The callback function has no arguments but may throw an exception. |
13 | fs.chmodSync(path, mode) <br>Synchronous chmod(). |
14 | fs.fchmod(fd, mode, callback) <br>Asynchronous fchmod(). The callback function has no arguments but may throw an exception. |
15 | fs.fchmodSync(fd, mode) <br>Synchronous fchmod(). |
16 | fs.lchmod(path, mode, callback) <br>Asynchronous lchmod(). The callback function has no arguments but may throw an exception. Only available on Mac OS X. |
17 | fs.lchmodSync(path, mode) <br>Synchronous lchmod(). |
18 | fs.stat(path, callback) <br>Asynchronous stat(). The callback function has two arguments err, stats, where stats is an fs.Stats object. |
19 | fs.lstat(path, callback) <br>Asynchronous lstat(). The callback function has two arguments err, stats, where stats is an fs.Stats object. |
20 | fs.fstat(fd, callback) <br>Asynchronous fstat(). The callback function has two arguments err, stats, where stats is an fs.Stats object. |
21 | fs.statSync(path) <br>Synchronous stat(). Returns an instance of fs.Stats. |
22 | fs.lstatSync(path) <br>Synchronous lstat(). Returns an instance of fs.Stats. |
23 | fs.fstatSync(fd) <br>Synchronous fstat(). Returns an instance of fs.Stats. |
24 | fs.link(srcpath, dstpath, callback) <br>Asynchronous link(). The callback function has no arguments but may throw an exception. |
25 | fs.linkSync(srcpath, dstpath) <br>Synchronous link(). |
26 | fs.symlink(srcpath, dstpath[, type], callback) <br>Asynchronous symlink(). The callback function has no arguments but may throw an exception. The type parameter can be set to 'dir', 'file', or 'junction' (default is 'file'). |
27 | fs.symlinkSync(srcpath, dstpath[, type]) <br>Synchronous symlink(). |
28 | fs.readlink(path, callback) <br>Asynchronous readlink(). The callback function has two arguments err, linkString. |
29 | fs.realpath(path[, cache], callback) <br>Asynchronous realpath(). The callback function has two arguments err, resolvedPath. |
30 | fs.realpathSync(path[, cache]) <br>Synchronous realpath(). Returns the absolute path. |
31 | fs.unlink(path, callback) <br>Asynchronous unlink(). The callback function has no arguments, but may throw exceptions. |
32 | fs.unlinkSync(path) <br>Synchronous unlink(). |
33 | fs.rmdir(path, callback) <br>Asynchronous rmdir(). The callback function has no arguments, but may throw exceptions. |
34 | fs.rmdirSync(path) <br>Synchronous rmdir(). |
35 | fs.mkdir(path[, mode], callback) <br>Asynchronous mkdir(2). The callback function has no arguments, but may throw exceptions. The default access permission is 0777. |
36 | fs.mkdirSync(path[, mode]) <br>Synchronous mkdir(). |
37 | fs.readdir(path, callback) <br>Asynchronous readdir(3). Reads the contents of a directory. |
38 | fs.readdirSync(path) <br>Synchronous readdir(). Returns an array of file listings. |
39 | fs.close(fd, callback) <br>Asynchronous close(). The callback function has no arguments, but may throw exceptions. |
40 | fs.closeSync(fd) <br>Synchronous close(). |
41 | fs.open(path, flags[, mode], callback) <br>Asynchronously opens a file. |
42 | fs.openSync(path, flags[, mode]) <br>Synchronous version of fs.open(). |
43 | fs.utimes(path, atime, mtime, callback) <br> |
44 | fs.utimesSync(path, atime, mtime) <br>Modifies the timestamps of a file specified by the file path. |
45 | fs.futimes(fd, atime, mtime, callback) <br> |
46 | fs.futimesSync(fd, atime, mtime) <br>Modifies the timestamps of a file specified by the file descriptor. |
47 | fs.fsync(fd, callback) <br>Asynchronous fsync. The callback function has no arguments, but may throw exceptions. |
48 | fs.fsyncSync(fd) <br>Synchronous fsync. |
49 | fs.write(fd, buffer, offset, length[, position], callback) <br>Writes buffer content to the file specified by the file descriptor. |
50 | fs.write(fd, data[, position[, encoding]], callback) <br>Writes file content via file descriptor fd. |
51 | fs.writeSync(fd, buffer, offset, length[, position]) <br>Synchronous version of fs.write(). |
52 | fs.writeSync(fd, data[, position[, encoding]]) <br>Synchronous version of fs.write(). |
53 | fs.read(fd, buffer, offset, length, position, callback) <br>Reads file content via file descriptor fd. |
54 | fs.readSync(fd, buffer, offset, length, position) <br>Synchronous version of fs.read. |
55 | fs.readFile(filename[, options], callback) <br>Asynchronously reads the entire contents of a file. |
56 | fs.readFileSync(filename[, options]) <br> |
57 | fs.writeFile(filename, data[, options], callback) <br>Asynchronously writes data to a file. |
58 | fs.writeFileSync(filename, data[, options]) <br>Synchronous version of fs.writeFile. |
59 | fs.appendFile(filename, data[, options], callback) <br>Asynchronously appends data to a file. |
60 | fs.appendFileSync(filename, data[, options]) <br>The synchronous version of fs.appendFile. |
61 | fs.watchFile(filename[, options], listener) <br>Watch for changes to the file. |
62 | fs.unwatchFile(filename[, listener]) <br>Stop watching for changes to filename. |
63 | fs.watch(filename[, options][, listener]) <br>Watch for changes to filename, which can be a file or directory. Returns an fs.FSWatcher object. |
64 | fs.exists(path, callback) <br>Check if the given path exists. |
65 | fs.existsSync(path) <br>Synchronous version of fs.exists. |
66 | fs.access(path[, mode], callback) <br>Test the permissions of a specified path. |
67 | fs.accessSync(path[, mode]) <br>Synchronous version of fs.access. |
68 | fs.createReadStream(path[, options]) <br>Returns a ReadStream object. |
69 | fs.createWriteStream(path[, options]) <br>Returns a WriteStream object. |
70 | fs.symlink(srcpath, dstpath[, type], callback) <br>Asynchronous symlink(). The callback function has no arguments but may throw an exception. |
For more details, please refer to the official documentation on the File System module: File System.