Node.js file system
Node.js provides a set of file operation APIs similar to UNIX (POSIX) standards. The syntax of Node's import file system module (fs) is as follows:
var fs = require("fs")
Asynchronous and synchronous
The methods in the Node.js file system (fs module) module are both asynchronous and synchronous Version, for example, functions for reading file contents include asynchronous fs.readFile() and synchronous fs.readFileSync().
The last parameter of the asynchronous method function is the callback function, and the first parameter of the callback function contains error information (error).
It is recommended that you use asynchronous methods. Compared with synchronization, asynchronous methods have higher performance, faster speed, and no blocking.
Example
Create the input.txt file with the following content:
php中文网官网地址:www.php.cn 文件读取实例
Create the file.js file with the following code:
var fs = require("fs"); // 异步读取 fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("异步读取: " + data.toString()); }); // 同步读取 var data = fs.readFileSync('input.txt'); console.log("同步读取: " + data.toString()); console.log("程序执行完毕。");
The above code execution results are as follows :
$ node file.js 同步读取: php中文网官网地址:www.php.cn 文件读取实例 程序执行完毕。 异步读取: php中文网官网地址:www.php.cn 文件读取实例
Next, let’s take a closer look at the Node.js file system method.
Open file
Syntax
The following is the syntax format for opening a file in asynchronous mode:
fs.open(path, flags[, mode], callback)
Parameters
Parameter usage instructions are as follows:
path - the path to the file.
flags - File opening behavior. See below for specific values.
mode - Set the file mode (permissions). The default permissions for file creation are 0666 (readable, writable).
callback - Callback function, with two parameters such as: callback(err, fd).
#flags parameter can have the following values:
Flag | Description |
---|---|
r | Open the file in read mode. Throws an exception if the file does not exist. |
r+ | Open the file in read-write mode. Throws an exception if the file does not exist. |
rs | Read files synchronously. |
rs+ | Read and write files synchronously. |
w | Open the file in writing mode, creating it if it does not exist. |
wx | Like 'w', but if the file path exists, file writing fails. |
w+ | Open the file in read-write mode and create it if it does not exist. |
wx+ | Similar to 'w+', but if the file path exists, the file reading and writing will fail. |
a | Open the file in append mode, creating it if it does not exist. |
ax | Similar to 'a', but if the file path exists, file appending fails. |
a+ | Open the file in read-append mode, creating it if it does not exist. |
ax+ | Similar to 'a+', but if the file path exists, file reading and appending will fail. |
Example
Next we create the file.js file and open the input.txt file for reading and writing. The code is as follows:
var fs = require("fs"); // 异步打开文件 console.log("准备打开文件!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("文件打开成功!"); });
The execution results of the above code are as follows:
$ node file.js 准备打开文件! 文件打开成功!
Get file information
Syntax
The following is the syntax format for obtaining file information through asynchronous mode:
fs.stat(path, callback)
Parameters
Parameters Instructions for use are as follows:
path - file path.
callback - Callback function, with two parameters such as: (err, stats), stats is the fs.Stats object.
After fs.stat(path) is executed, the instance of the stats class will be returned to its callback function. You can determine the relevant attributes of the file through the provided methods in the stats class. For example, to determine 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 are:
Description | |
---|---|
Returns true if it is a file, otherwise returns false. | |
Returns true if it is a directory, otherwise returns false. | |
Returns true if it is a block device, otherwise returns false. | |
Returns true if it is a character device, otherwise returns false. | |
Returns true if it is a soft link, otherwise returns false. | |
If it is FIFO, return true, otherwise return false. FIFO is a special type of command pipe in UNIX. | |
If it is a Socket, return true, otherwise return false. |
Serial number | Method & Description |
---|---|
1 | fs.rename(oldPath, newPath, callback) Asynchronous rename(). The callback function has no parameters, but may throw an exception. |
2 | fs.ftruncate(fd, len, callback) Asynchronous ftruncate(). The callback function has no parameters, but may throw an exception. |
3 | fs.ftruncateSync(fd, len) Sync ftruncate() |
4 | ##fs.truncate(path, len, callback)Asynchronous truncate(). The callback function has no parameters, but may throw an exception. |
fs.truncateSync(path, len)Sync truncate() | |
##fs.chown(path, uid, gid, callback) | Asynchronous chown(). The callback function has no parameters, but may throw an exception. |
fs.chownSync(path, uid, gid) | Sync chown() |
fs.fchown(fd, uid, gid, callback) | Asynchronous fchown(). The callback function has no parameters, but may throw an exception. |
fs.fchownSync(fd, uid, gid) | Sync fchown() |
fs.lchown(path, uid, gid, callback) | Asynchronous lchown(). The callback function has no parameters, but may throw an exception. |
fs.lchownSync(path, uid, gid) | Sync lchown() |
fs.chmod(path, mode, callback) | Asynchronous chmod(). The callback function has no parameters, but may throw an exception. |
fs.chmodSync(path, mode) | Sync chmod(). |
fs.fchmod(fd, mode, callback) | Asynchronous fchmod(). The callback function has no parameters, but may throw an exception. |
fs.fchmodSync(fd, mode) | Sync fchmod(). |
fs.lchmod(path, mode, callback) | Asynchronous lchmod(). The callback function has no parameters, but may throw an exception. Only available on Mac OS X. |
fs.lchmodSync(path, mode) | Sync lchmod(). |
fs.stat(path, callback) | Asynchronous stat(). The callback function has two parameters err, stats, stats Is the fs.Stats object. |
fs.lstat(path, callback) | Asynchronous lstat(). The callback function has two parameters err, stats , stats is the fs.Stats object. |
fs.fstat(fd, callback) | Asynchronous fstat(). The callback function has two parameters err, stats , stats is the fs.Stats object. |
fs.statSync(path) | Synchronize stat(). Returns an instance of fs.Stats. |
fs.lstatSync(path) | Synchronize lstat(). Returns an instance of fs.Stats. |
fs.fstatSync(fd) | Synchronous fstat(). Returns an instance of fs.Stats. |
24 | fs.link(srcpath, dstpath, callback) Asynchronous link(). The callback function has no parameters, but may throw an exception. |
25 | fs.linkSync(srcpath, dstpath) Sync link(). |
26 | fs.symlink(srcpath, dstpath[, type], callback) Asynchronous 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]) Synchronize symlink(). |
28 | fs.readlink(path, callback) Asynchronous readlink(). The callback function has two parameters err, linkString. |
29 | fs.realpath(path[, cache], callback) Asynchronous realpath(). There are two callback functions Parameters err, resolvedPath. |
30 | fs.realpathSync(path[, cache]) Synchronize realpath(). Returns the absolute path. |
31 | fs.unlink(path, callback) Asynchronous unlink(). The callback function has no parameters, but may throw abnormal. |
32 | fs.unlinkSync(path) Sync unlink(). |
33 | fs.rmdir(path, callback) Asynchronous rmdir(). The callback function has no parameters, but may throw an exception. |
34 | fs.rmdirSync(path) Sync rmdir(). |
35 | fs.mkdir(path[, mode], callback) S Asynchronous mkdir(2). The callback function has no parameters, but may throw an exception. mode defaults to 0777. |
36 | fs.mkdirSync(path[, mode]) Sync mkdir(). |
37 | fs.readdir(path, callback) Asynchronous readdir(3). Read the contents of the directory. |
38 | fs.readdirSync(path) Synchronous readdir(). Returns a file array list. |
39 | fs.close(fd, callback) Asynchronous close(). The callback function has no parameters, but may throw abnormal. |
40 | fs.closeSync(fd) Sync close(). |
41 | fs.open(path, flags[, mode], callback) Open the file asynchronously. |
42 | fs.openSync(path, flags[, mode]) Sync version of fs.open(). |
43 | fs.utimes(path, atime, mtime, callback) |
fs.utimesSync(path, atime, mtime)Modify the file timestamp, and the file passes the specified file path. | |
fs.futimes(fd, atime, mtime, callback) | |
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) Sync fsync. |
fs.write(fd, buffer, offset, length[, position], callback)Write the buffer contents to the file specified by the file descriptor. | |
fs.write(fd, data[, position[, encoding]], callback)Pass file descriptor fd writes the contents of the file. | |
fs.writeSync(fd, buffer, offset, length[, position])Synchronized version of fs.write (). | |
fs.writeSync(fd, data[, position[, encoding]])Synchronized version of fs.write (). | |
fs.read(fd, buffer, offset, length, position, callback) | Through file description The symbol fd reads the contents of the file. |
fs.readSync(fd, buffer, offset, length, position) | Synchronized version of fs.read. |
fs.readFile(filename[, options], callback) | Read the file content asynchronously. |
fs.readFileSync(filename[, options]) | <brSynchronized version of fs.readfile.<="" td=""> | ##57
Write file content asynchronously. | 58 |
Synchronous version of fs.writeFile. | 59 |
Append file content asynchronously. | 60 |
The synchronization version of fs.appendFile. | 61 |
View file modifications. | 62 |
Stop viewing modifications to filename. | 63 |
View the modification of filename, filename can be file or directory. Returns an fs.FSWatcher object. | 64 |
Detects whether the given path exists. | 65 |
Synchronized version of fs.exists. | 66 |
Test the user permissions on the specified path. | 67 |
Synchronized version of fs.access. | 68 |
Returns the ReadStream object. | 69 |
Return a WriteStream object. | |
70 | fs.symlink(srcpath, dstpath[, type], callback) Asynchronous symlink(). There is no callback function parameters, but may throw an exception. |
For more information, please view the official website file module description: File System.