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:

FlagDescription
rOpen 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.
wOpen the file in writing mode, creating it if it does not exist.
wxLike '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.
aOpen the file in append mode, creating it if it does not exist.
axSimilar 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:

##MethodDescriptionstats.isFile()Returns true if it is a file, otherwise returns false. stats.isDirectory()Returns true if it is a directory, otherwise returns false. stats.isBlockDevice()Returns true if it is a block device, otherwise returns false. stats.isCharacterDevice()Returns true if it is a character device, otherwise returns false. stats.isSymbolicLink()Returns true if it is a soft link, otherwise returns false. stats.isFIFO()If it is FIFO, return true, otherwise return false. FIFO is a special type of command pipe in UNIX. stats.isSocket()If it is a Socket, return true, otherwise return false.

Example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("准备打开文件!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }
   console.log(stats);
   console.log("读取文件信息成功!");
   
   // 检测文件类型
   console.log("是否为文件(isFile) ? " + stats.isFile());
   console.log("是否为目录(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) }
读取文件信息成功!
是否为文件(isFile) ? true
是否为目录(isDirectory) ? false

Write the file

Syntax

The following is the syntax format for writing files in asynchronous mode:

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

If the file exists, the content written by this method will overwrite the old file content.

Parameters

The parameter usage instructions are as follows:

  • path - file path.

  • #data - The data to be written to the file, which can be a String or Buffer object.

  • options - The parameter is an object containing {encoding, mode, flag}. The default encoding is utf8, the mode is 0666, the flag is 'w'

  • callback - callback function, the callback function only contains error information parameters (err), when writing Returned if entry fails.

Example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("准备写入文件");
fs.writeFile('input.txt', '我是通过写入的文件内容!',  function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("数据写入成功!");
   console.log("--------我是分割线-------------")
   console.log("读取写入的数据!");
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("异步读取文件数据: " + data.toString());
   });
});

The execution result of the above code is as follows:

$ node file.js 
准备写入文件
数据写入成功!
--------我是分割线-------------
读取写入的数据!
异步读取文件数据: 我是通过写入的文件内容

Reading files

Syntax

The following is the syntax format for reading files in asynchronous mode:

fs.read(fd, buffer, offset, length, position, callback)

This method uses a file descriptor to read Get the file.

Parameters

The parameter usage instructions are as follows:

  • fd - the file descriptor returned by the fs.open() method .

  • #buffer - The buffer to which data is written.

  • #offset - The write offset for buffer writes.

  • #length - The number of bytes to read from the file.

  • position - The starting position for file reading. If the value of position is null, it will be read from the position of the current file pointer.

  • callback - Callback function, has three parameters err, bytesRead, buffer, err is the error message, bytesRead represents the number of bytes read, and buffer is the buffer area object.

Example

The input.txt file content is:

php中文网官网地址:www.php.cn

Next we create the file.js file, the code is as follows:

var fs = require("fs");
var buf = new Buffer(1024);

console.log("准备打开已存在的文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("文件打开成功!");
   console.log("准备读取文件:");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + "  字节被读取");
      
      // 仅输出读取的字节
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

The above code execution results are as follows:

$ node file.js 
准备打开已存在的文件!
文件打开成功!
准备读取文件:
42  字节被读取
php中文网官网地址:www.php.cn

Close the file

Syntax

The following is the syntax format for closing the file in asynchronous mode:

fs.close(fd, callback)

This method uses a file descriptor to read the file.

Parameters

The parameter usage instructions are as follows:

  • fd - the file descriptor returned by the fs.open() method .

  • callback - Callback function, no parameters.

Example

The input.txt file content is:

php中文网官网地址:www.php.cn

Next we create the file.js file, the code is as follows:

var fs = require("fs");
var buf = new Buffer(1024);

console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(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 
准备打开文件!
文件打开成功!
准备读取文件!
php中文网官网地址:www.php.cn
文件关闭成功

Intercept file

Syntax

The following is the syntax format for intercepting files in asynchronous mode:

fs.ftruncate(fd, len, callback)

This method uses a file descriptor to read the file.

Parameters

The parameter usage instructions are as follows:

  • fd - the file descriptor returned by the fs.open() method .

  • #len - The length of the truncated file content.

  • callback - Callback function, no parameters.

Example

The input.txt file content is:

site:www.php.cn

Next we create the file.js file, the code is as follows:

var fs = require("fs");
var buf = new Buffer(1024);

console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("文件打开成功!");
   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
文件关闭成功

Delete file

Syntax

The following is the syntax format for deleting files:

fs.unlink(path, callback)

Parameter

Parameter usage instructions are as follows:

  • path - file path.

  • callback - Callback function, no parameters.

Example

The input.txt file content is:

site:www.php.cn

Next we create the file.js file, the code is as follows:

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 
准备删除文件!
文件删除成功!

Check the input.txt file again and find that it no longer exists.


Create directory

Syntax

The following is the syntax format for creating a directory:

fs.mkdir(path[, mode], callback)

Parameters

The parameter usage instructions are as follows :

  • #path - file path.

  • #mode - Set directory permissions, default is 0777.

  • callback - Callback function, no parameters.

Example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("创建目录 /tmp/test/");
fs.mkdir("/tmp/test/",function(err){
   if (err) {
       return console.error(err);
   }
   console.log("目录创建成功。");
});

The execution result of the above code is as follows:

$ node file.js 
创建目录 /tmp/test/
目录创建成功。

Read directory

Syntax

The following is the syntax format for reading the directory:

fs.readdir(path, callback)

Parameters

The parameter usage instructions are as follows:

  • #path - file path.

  • callback - Callback function, the callback function takes two parameters err, files, err is the error message, and files is the file array list in the directory.

Example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("查看 /tmp 目录");
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 
查看 /tmp 目录
input.out
output.out
test
test.txt

Delete directory

Syntax

The following is the syntax format for deleting a directory:

fs.rmdir(path, callback)

Parameters

The parameter usage instructions are as follows:

  • path - File path.

  • callback - Callback function, no parameters.

Example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("准备删除目录 /tmp/test");
fs.rmdir("/tmp/test",function(err){
   if (err) {
       return console.error(err);
   }
   console.log("读取 /tmp 目录");
   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 
准备删除目录 /tmp/test
input.out
output.out
test
test.txt
读取 /tmp 目录
……

File Module Method Reference Manual

The following is a list of the same methods in Node.js file module:

56##fs.chown(path, uid, gid, callback)7fs.chownSync(path, uid, gid)8fs.fchown(fd, uid, gid, callback)9fs.fchownSync(fd, uid, gid)10fs.lchown(path, uid, gid, callback)11fs.lchownSync(path, uid, gid)12fs.chmod(path, mode, callback)13fs.chmodSync(path, mode)14fs.fchmod(fd, mode, callback)15fs.fchmodSync(fd, mode)16fs.lchmod(path, mode, callback)17fs.lchmodSync(path, mode)18fs.stat(path, callback)19fs.lstat(path, callback)20fs.fstat(fd, callback)21fs.statSync(path)22fs.lstatSync(path)23fs.fstatSync(fd)# #444546##49 505152##53fs.read(fd, buffer, offset, length, position, callback)54fs.readSync(fd, buffer, offset, length, position)55fs.readFile(filename[, options], callback)56fs.readFileSync(filename[, options])##57##fs.writeFile(filename, data[, options], callback)Write file content asynchronously. fs.writeFileSync(filename, data[, options]) Synchronous version of fs.writeFile. fs.appendFile(filename, data[, options], callback)Append file content asynchronously. fs.appendFileSync(filename, data[, options])The synchronization version of fs.appendFile.fs.watchFile(filename[, options], listener)View file modifications. fs.unwatchFile(filename[, listener])Stop viewing modifications to filename. fs.watch(filename[, options][, listener])View the modification of filename, filename can be file or directory. Returns an fs.FSWatcher object. fs.exists(path, callback)Detects whether the given path exists. fs.existsSync(path)Synchronized version of fs.exists.fs.access(path[, mode], callback)Test the user permissions on the specified path. fs.accessSync(path[, mode])Synchronized version of fs.access. fs.createReadStream(path[, options])Returns the ReadStream object. fs.createWriteStream(path[, options])Return a WriteStream object.
Serial numberMethod & Description
1fs.rename(oldPath, newPath, callback)
Asynchronous rename(). The callback function has no parameters, but may throw an exception.
2fs.ftruncate(fd, len, callback)
Asynchronous ftruncate(). The callback function has no parameters, but may throw an exception.
3fs.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()
Asynchronous chown(). The callback function has no parameters, but may throw an exception.
Sync chown()
Asynchronous fchown(). The callback function has no parameters, but may throw an exception.
Sync fchown()
Asynchronous lchown(). The callback function has no parameters, but may throw an exception.
Sync lchown()
Asynchronous chmod(). The callback function has no parameters, but may throw an exception.
Sync chmod().
Asynchronous fchmod(). The callback function has no parameters, but may throw an exception.
Sync fchmod().
Asynchronous lchmod(). The callback function has no parameters, but may throw an exception. Only available on Mac OS X.
Sync lchmod().
Asynchronous stat(). The callback function has two parameters err, stats, stats Is the fs.Stats object.
Asynchronous lstat(). The callback function has two parameters err, stats , stats is the fs.Stats object.
Asynchronous fstat(). The callback function has two parameters err, stats , stats is the fs.Stats object.
Synchronize stat(). Returns an instance of fs.Stats.
Synchronize lstat(). Returns an instance of fs.Stats.
Synchronous fstat(). Returns an instance of fs.Stats.
24fs.link(srcpath, dstpath, callback)
Asynchronous link(). The callback function has no parameters, but may throw an exception.
25fs.linkSync(srcpath, dstpath)
Sync link().
26fs.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').
27fs.symlinkSync(srcpath, dstpath[, type])
Synchronize symlink().
28fs.readlink(path, callback)
Asynchronous readlink(). The callback function has two parameters err, linkString.
29fs.realpath(path[, cache], callback)
Asynchronous realpath(). There are two callback functions Parameters err, resolvedPath.
30fs.realpathSync(path[, cache])
Synchronize realpath(). Returns the absolute path.
31fs.unlink(path, callback)
Asynchronous unlink(). The callback function has no parameters, but may throw abnormal.
32fs.unlinkSync(path)
Sync unlink().
33fs.rmdir(path, callback)
Asynchronous rmdir(). The callback function has no parameters, but may throw an exception.
34fs.rmdirSync(path)
Sync rmdir().
35fs.mkdir(path[, mode], callback)
S ​​Asynchronous mkdir(2). The callback function has no parameters, but may throw an exception. mode defaults to 0777.
36fs.mkdirSync(path[, mode])
Sync mkdir().
37fs.readdir(path, callback)
Asynchronous readdir(3). Read the contents of the directory.
38fs.readdirSync(path)
Synchronous readdir(). Returns a file array list.
39fs.close(fd, callback)
Asynchronous close(). The callback function has no parameters, but may throw abnormal.
40fs.closeSync(fd)
Sync close().
41fs.open(path, flags[, mode], callback)
Open the file asynchronously.
42fs.openSync(path, flags[, mode])
Sync version of fs.open().
43fs.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.
47fs.fsync(fd, callback)
Asynchronous fsync. The callback function has no parameters, but may throw an exception.
48fs.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 ().
Through file description The symbol fd reads the contents of the file.
Synchronized version of fs.read.
Read the file content asynchronously.
<brSynchronized version of fs.readfile.<="" td="">

58

59

60

61

62

63

64

65

66

67

68

69
70fs.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.