English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node FS is an in-built module in Node.js that helps you handle files and perform operations on them.
Using Node FS, you can perform the following operations on files:
Read file
Create or overwrite file
Update file
删除文件
Rename file
Node.js provides a set of file operation APIs similar to UNIX (POSIX) standards.
The syntax for importing the file system module (fs) in Node is as shown below:
var fs = require("fs")
The methods in the Node.js file system (fs module) module have both asynchronous and synchronous versions, for example, the function to read the content of a file has the asynchronous fs.readFile() and the synchronous fs.readFileSync().
The last parameter of the asynchronous method function is the callback function, which contains the error information (error).
It is recommended to use asynchronous methods, as they are more performant, faster, and non-blocking compared to synchronous methods.
Create a file named input.txt with the following content:
Basic tutorial official website address: www.oldtoolbag.com File read example
Create a file named file.js 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 completed.");
The execution result of the above code is as follows:
$ node file.js Synchronous read: Basic tutorial official website address: www.oldtoolbag.com File read example Program execution completed. Asynchronous read: Basic tutorial official website address: www.oldtoolbag.com File read example
Next, let's take a specific look at the Node.js file system methods.
The syntax format for opening a file in asynchronous mode is as follows:
fs.open(path, flags[, mode], callback)
Parameter usage instructions are as follows:
path - The path of the file.
flags - The behavior of file opening. Specific values are detailed below.
mode - Set file mode (permissions), the default permission for file creation is 0666(Readable, writable).
callback - Callback function, with two parameters such as: callback(err, fd).
The flags parameter can be one of the following values:
Flag | Description |
---|---|
r | Open the file in read mode. If the file does not exist, an exception will be thrown. |
r+ | Open the file in read and write mode. If the file does not exist, an exception will be thrown. |
rs | Read files synchronously. |
rs+ | Read and write files synchronously. |
w | Open the file in write mode, if the file does not exist, it will be created. |
wx | Similar to 'w', but if the file path exists, the file write will fail. |
w+ | Open the file in read and write mode, if the file does not exist, it will be created. |
wx+ | Similar to 'w+However, if the file path exists, the file read and write will fail. |
a | Open the file in append mode, if the file does not exist, it will be created. |
ax | Similar to 'a', but if the file path exists, the file append will fail. |
a+ | Open the file in read append mode, if the file does not exist, it will be created. |
ax+ | Similar to 'a+However, if the file path exists, the file read append will fail. |
Next, we create the file.js file and open the input.txt file for reading and writing, as shown in the code below:
var fs = require("fs"); // Asynchronous file opening console.log("Preparing to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); });
The execution result of the above code is as follows:
$ node file.js 准备打开文件! 文件打开成功!
The following is the syntax format for getting file information asynchronously:
fs.stat(path, callback)
Parameter usage instructions are as follows:
path - File path.
callback - Callback function, with two parameters such as: (err, stats), stats is fs.Stats object.
After fs.stat(path) is executed, an instance of the stats class will be returned to its callback function. You can judge the relevant properties of the file through the methods provided by the stats class. For example, to judge whether 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() | If it is a file, return true; otherwise, return false. |
stats.isDirectory() | If it is a directory, return true; otherwise, return false. |
stats.isBlockDevice() | If it is a block device, return true; otherwise, return false. |
stats.isCharacterDevice() | If it is a character device, return true; otherwise, return false. |
stats.isSymbolicLink() | If it is a symbolic link, return true, otherwise return false. |
stats.isFIFO() | If it is a FIFO, return true, otherwise return false. FIFO is a special type of command pipeline in UNIX. |
stats.isSocket() | If it is a Socket, return true, otherwise return false. |
Next, we create the file.js file, as shown below:
var fs = require("fs"); console.log("Preparing to open file!"); fs.stat('input.txt', function(err, stats) { if (err) { return console.error(err); } console.log(stats); console.log("File information read successfully!"); // File type detection console.log("Is it a file (isFile)? "); + stats.isFile()); console.log("Is it a directory (isDirectory)? "); + stats.isDirectory()); });
The execution result of the above code is as follows:
$ node file.js 准备打开文件! { 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
The following is the syntax format for writing files in asynchronous mode:
fs.writeFile(file, data[, options], callback)
The default file opening mode of writeFile is w mode, so if the file exists, the content written by this method will overwrite the old file content.
Parameter usage instructions are as follows:
file - Filename or file descriptor.
data - The data to be written to the file, which can be a String (string) or Buffer (buffer) object.
options - This parameter is an object containing {encoding, mode, flag}. The default encoding is utf8, mode is 0666 , with flag 'w'
callback - The callback function, which only contains the error information parameter (err), is returned when the writing fails.
Next, we create the file.js file, as shown below:
var fs = require("fs"); console.log("Preparing to write file"); fs.writeFile('input.txt', 'I am writing through fs.writeFile', function(err) { if (err) { return console.error(err); } console.log("Data written successfully!"); console.log("--------I am a separator-------------") console.log("Read the written data!"); fs.readFile('input.txt', function(err, data) { if (err) { return console.error(err); } console.log("Asynchronous reading file data: ", + data.toString()); }); });
The execution result of the above code is as follows:
$ node file.js Preparing to write file Data written successfully! --------I am a separator------------- Read the written data! Asynchronous reading file data: I am through fs.writeFile writing file content
The following is the syntax format 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.
Parameter usage instructions are as follows:
fd - The file descriptor returned by fs.open().
buffer - The buffer for data writing.
offset - The write offset in the buffer.
length - The number of bytes to be read from the file.
position - The starting position of file reading, if the value of position is null, it will read from the current file pointer position.
callback - The callback function, with three parameters err, bytesRead, buffer, err is the error information, bytesRead indicates the number of bytes read, buffer is the buffer object.
input.txt 文件内容为:
Basic tutorial official website address: www.oldtoolbag.com
Next, we create the file.js file, as shown below:
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 file:"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) { if (err) { console.log(err); } console.log(bytes + " 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! 文件打开成功! Preparing to read file: 42 Bytes read Basic tutorial official website address: www.oldtoolbag.com
The following is the syntax format for closing a file in asynchronous mode:
fs.close(fd, callback)
This method uses a file descriptor to read the file.
Parameter usage instructions are as follows:
fd - The file descriptor returned by fs.open().
callback - Callback function, no parameters.
input.txt 文件内容为:
Basic tutorial official website address: www.oldtoolbag.com
Next, we create the file.js file, as shown below:
var fs = require("fs"); var buf = new Buffer.alloc(1024); console.log("Preparing to open 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 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("File closed successfully"); }); }); });
The execution result of the above code is as follows:
$ node file.js 准备打开文件! 文件打开成功! Preparing to read file! Basic tutorial official website address: www.oldtoolbag.com 文件关闭成功
The following is the syntax format for truncating a file in asynchronous mode:
fs.ftruncate(fd, len, callback)
This method uses a file descriptor to read the file.
Parameter usage instructions are as follows:
fd - The file descriptor returned by fs.open().
len - The length of the file content to be截取.
callback - Callback function, no parameters.
input.txt 文件内容为:
site:www.oldtoolbag.com
Next, we create the file.js file, as shown below:
var fs = require("fs"); var buf = new Buffer.alloc(1024); console.log("Preparing to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("截取"}}10字节内的文件内容,超出部分将被去除。 // 截取文件 fs.ftruncate(fd, 10, function(err) { if (err) { console.log(err); } console.log("文件截取成功。"); console.log("读取相同的文件"); 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("文件关闭成功!"); }); }); }); });
The execution result of the above code is as follows:
$ node file.js 准备打开文件! 文件打开成功! 截取10字节内的文件内容,超出部分将被去除。 文件截取成功。 读取相同的文件 site:www.r 文件关闭成功
以下为删除文件的语法格式:
fs.unlink(path, callback)
Parameter usage instructions are as follows:
path - File path.
callback - Callback function, no parameters.
input.txt 文件内容为:
site:www.oldtoolbag.com
Next, we create the file.js file, as shown below:
var fs = require("fs"); console.log("准备删除文件!"); fs.unlink('input.txt', function(err) { if (err) { return console.error(err); } console.log("文件删除成功!"); });
The execution result of the above code is as follows:
$ node file.js 准备删除文件! 文件删除成功!
再去查看 input.txt 文件,发现已经不存在了。
以下为创建目录的语法格式:
fs.mkdir(path[, options], callback)
Parameter usage instructions are as follows:
path - File path.
options 参数可以是:
recursive - 是否以递归的方式创建目录,默认为 false。
mode - 设置目录权限,默认为 0777.
callback - Callback function, no parameters.
Next, we create the file.js file, as shown below:
var fs = require("fs"); // tmp 目录必须存在 console.log("创建目录 /tmp/test/"); fs.mkdir("/tmp/test/ if (err) { return console.error(err); } console.log("目录创建成功。"); });
The execution result of the above code is as follows:
$ node file.js 创建目录 /tmp/test/ 目录创建成功。
可以添加 recursive: true 参数,不管创建的目录 /tmp 和 /tmp/a 是否存在:
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; });
The following is the syntax format for reading a directory:
fs.readdir(path, callback)
Parameter usage instructions are as follows:
path - File path.
callback - Callback function, the callback function has two parameters err, files, err is the error information, files is the array list of files in the directory.
Next, we create the file.js file, as shown below:
var fs = require("fs"); console.log("View /tmp Directory"); fs.readdir("/tmp/",function(err, files){ if (err) { return console.error(err); } files.forEach(function(file){ console.log(file); }); });
The execution result of the above code is as follows:
$ node file.js View /tmp Directory input.out output.out test test.txt
The following is the syntax format for deleting a directory:
fs.rmdir(path, callback)
Parameter usage instructions are as follows:
path - File path.
callback - Callback function, no parameters.
Next, we create the file.js file, as shown below:
var fs = require("fs"); // Create an empty one before execution /tmp/test Directory console.log("Prepare to delete directory /tmp/test"); fs.rmdir("/tmp/test", function(err){ if (err) { return console.error(err); } console.log("Read /tmp Directory"); fs.readdir("/tmp/",function(err, files){ if (err) { return console.error(err); } files.forEach(function(file){ console.log(file); }); }); });
The execution result of the above code is as follows:
$ node file.js Prepare to delete the directory /tmp/test Read /tmp Directory ……
The following is a list of the same methods in the Node.js file module:
Serial Number | Method & Description |
---|---|
1 | fs.rename(oldPath, newPath, callback) The callback function of async rename() has no parameters, but may throw an exception. |
2 | fs.ftruncate(fd, len, callback) The callback function of async ftruncate() has no parameters, but may throw an exception. |
3 | fs.ftruncateSync(fd, len) Synchronous ftruncate() |
4 | fs.truncate(path, len, callback) The callback function of async truncate() has no parameters, but may throw an exception. |
5 | fs.truncateSync(path, len) Synchronize truncate(). |
6 | fs.chown(path, uid, gid, callback) Asynchronous chown(). The callback function takes no parameters but may throw an exception. |
7 | fs.chownSync(path, uid, gid) Synchronize chown(). |
8 | fs.fchown(fd, uid, gid, callback) Asynchronous fchown(). The callback function takes no parameters but may throw an exception. |
9 | fs.fchownSync(fd, uid, gid) Synchronize fchown(). |
10 | fs.lchown(path, uid, gid, callback) Asynchronous lchown(). The callback function takes no parameters but may throw an exception. |
11 | fs.lchownSync(path, uid, gid) Synchronize lchown(). |
12 | fs.chmod(path, mode, callback) Asynchronous chmod(). The callback function takes no parameters but may throw an exception. |
13 | fs.chmodSync(path, mode) Synchronize chmod(). |
14 | fs.fchmod(fd, mode, callback) Asynchronous fchmod(). The callback function takes no parameters but may throw an exception. |
15 | fs.fchmodSync(fd, mode) Synchronize fchmod(). |
16 | fs.lchmod(path, mode, callback) Asynchronous lchmod(). The callback function takes no parameters but may throw an exception. Only available on Mac OS X. |
17 | fs.lchmodSync(path, mode) Synchronize lchmod(). |
18 | fs.stat(path, callback) Asynchronous stat(). The callback function takes two parameters err, stats, where stats is an fs.Stats object. |
19 | fs.lstat(path, callback) Asynchronous lstat(). The callback function takes two parameters err, stats, where stats is an fs.Stats object. |
20 | fs.fstat(fd, callback) Asynchronous fstat(). The callback function takes two parameters err, stats, where stats is an fs.Stats object. |
21 | fs.statSync(path) Synchronize stat(). Returns an instance of fs.Stats. |
22 | fs.lstatSync(path) Synchronously lstat(). Returns an instance of fs.Stats. |
23 | fs.fstatSync(fd) Synchronously fstat(). Returns an instance of fs.Stats. |
24 | fs.link(srcpath, dstpath, callback) Asynchronously link(). The callback function has no parameters, but may throw an exception. |
25 | fs.linkSync(srcpath, dstpath) Synchronously link(). |
26 | fs.symlink(srcpath, dstpath[, type], callback) Asynchronously symlink(). The callback function has no parameters, 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]) Synchronously symlink(). |
28 | fs.readlink(path, callback) Asynchronously readlink(). The callback function has two parameters err, linkString. |
29 | fs.realpath(path[, cache], callback) Asynchronously realpath(). The callback function has two parameters err, resolvedPath. |
30 | fs.realpathSync(path[, cache]) Synchronously realpath(). Returns an absolute path. |
31 | fs.unlink(path, callback) Asynchronously unlink(). The callback function has no parameters, but may throw an exception. |
32 | fs.unlinkSync(path) Synchronously unlink(). |
33 | fs.rmdir(path, callback) Asynchronously rmdir(). The callback function has no parameters, but may throw an exception. |
34 | fs.rmdirSync(path) Synchronously rmdir(). |
35 | fs.mkdir(path[, mode], callback) S asynchronously mkdir(2). The callback function has no parameters, but may throw an exception. The default access permission is 0777. |
36 | fs.mkdirSync(path[, mode]) Synchronously mkdir(). |
37 | fs.readdir(path, callback) Asynchronously readdir(3). Reads the contents of the directory. |
38 | fs.readdirSync(path) Synchronously readdir(). Returns an array list of files. |
39 | fs.close(fd, callback) Asynchronous close(). The callback function has no parameters but may throw an exception. |
40 | fs.closeSync(fd) Synchronous close(). |
41 | fs.open(path, flags[, mode], callback) Asynchronous file opening. |
42 | fs.openSync(path, flags[, mode]) Synchronous version of fs.open(). |
43 | fs.utimes(path, atime, mtime, callback) |
44 | fs.utimesSync(path, atime, mtime) Modify file timestamp, file specified by the specified file path. |
45 | fs.futimes(fd, atime, mtime, callback) |
46 | fs.futimesSync(fd, atime, mtime) Modify file timestamp, specified by file descriptor. |
47 | fs.fsync(fd, callback) Asynchronous fsync. The callback function has no parameters but may throw an exception. |
48 | fs.fsyncSync(fd) Synchronous fsync. |
49 | fs.write(fd, buffer, offset, length[, position], callback) Write the content of the buffer to the file specified by the file descriptor. |
50 | fs.write(fd, data[, position[, encoding]], callback) Write file content through file descriptor fd. |
51 | fs.writeSync(fd, buffer, offset, length[, position]) The synchronous version of fs.write(). |
52 | fs.writeSync(fd, data[, position[, encoding]]) The synchronous version of fs.write(). |
53 | fs.read(fd, buffer, offset, length, position, callback) Read file content through file descriptor fd. |
54 | fs.readSync(fd, buffer, offset, length, position) The synchronous version of fs.read. |
55 | fs.readFile(filename[, options], callback) Asynchronous reading of file content. |
56 | fs.readFileSync(filename[, options]) The synchronous version of fs.readFile. |
57 | fs.writeFile(filename, data[, options], callback) Asynchronously write file content. |
58 | fs.writeFileSync(filename, data[, options]) The synchronous version of fs.writeFile. |
59 | fs.appendFile(filename, data[, options], callback) Asynchronously append file content. |
60 | fs.appendFileSync(filename, data[, options]) The synchronous version of fs.appendFile. |
61 | fs.watchFile(filename[, options], listener) Check the modification of a file. |
62 | fs.unwatchFile(filename[, listener]) Stop checking the modification of filename. |
63 | fs.watch(filename[, options][, listener]) Check the modification of filename, which can be a file or a directory. Returns an fs.FSWatcher object. |
64 | fs.exists(path, callback) Check if the given path exists. |
65 | fs.existsSync(path) The synchronous version of fs.exists. |
66 | fs.access(path[, mode], callback) Test the user permissions of the specified path. |
67 | fs.accessSync(path[, mode]) The synchronous version of fs.access. |
68 | fs.createReadStream(path[, options]) Returns a ReadStream object. |
69 | fs.createWriteStream(path[, options]) Returns a WriteStream object. |
70 | fs.symlink(srcpath, dstpath[, type], callback) The asynchronous symlink(). The callback function has no parameters but may throw an exception. |
For more information, please refer to the official documentation of the file module on the website:File System.