Latest web development tutorials

Node.js file system

Node.js provides a similar set of UNIX (POSIX) standard file operations API. Node Import File System Module (fs) syntax is as follows:

var fs = require("fs")

Asynchronous and synchronous

Node.js file system (fs Module) module methods have asynchronous and synchronous versions, such as reading the content of the document function has asynchronous fs.readFile () and synchronization fs.readFileSync ().

Asynchronous method functions last parameter to the callback function, the first argument to the callback function contains an error message (error).

I recommend is to use asynchronous method, compared to synchronous, asynchronous method for higher-performance, faster, and there is no obstruction.

Examples

Create input.txt file, as follows:

本教程官网地址:www.w3big.com
文件读取实例

Create file.js file, as follows:

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 is executed as follows:

$ node file.js 
同步读取: 本教程官网地址:www.w3big.com
文件读取实例

程序执行完毕。
异步读取: 本教程官网地址:www.w3big.com
文件读取实例

Next, let us understand the specific methods under Node.js file system.


open a file

grammar

The following is an open file in asynchronous mode syntax:

fs.open(path, flags[, mode], callback)

parameter

Parameters as follows:

  • path - path to the file.

  • flags - file open behavior.Specific values ​​described below.

  • mode - set the file mode (permissions), create a file default permissions 0666 (readable, writable).

  • callback - callback function takes two parameters, such as: callback (err, fd).

flags parameter can be the following values:

Flag description
r Open the file in read mode. If the file does not exist throw.
r + Open the file in read-write mode. If the file does not exist throw.
rs Read the file in a synchronous manner.
rs + In a synchronized manner to read and write files.
w Open the file in write mode, if the file does not exist it is created.
wx Similar 'w', but if the file path exists, the file write failure.
w + Open the file in read-write mode, if the file does not exist it is created.
wx + Similar 'w +', but if the file path exists, the file read and write failed.
a Open the file in append mode, if the file does not exist it is created.
ax Similar to 'a', but if the file path exists, the file append fails.
a + To read the file opened in append mode, if the file does not exist it is created.
ax + Similar 'a +', but if the file path exists, the file is read additional failures.

Examples

Next we create file.js file and opens input.txt file read and write code 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 above code is executed as follows:

$ node file.js 
准备打开文件!
文件打开成功!

Getting file information

grammar

The following documents to obtain information through asynchronous mode syntax:

fs.stat(path, callback)

parameter

Parameters as follows:

  • path - file path.

  • callback - callback function takes two parameters, such as:(err, stats), stats are fs.Stats object.

After fs.stat (path) execution, an instance of the class will be returned to their stats callback function. You can determine the relevant attributes of the file by stats class provides a method. For example, to determine whether the files:

var fs = require('fs');

fs.stat('/Users/liuht/code/itbilu/demo/fs.js', function (err, stats) {
    console.log(stats.isFile()); 		//true
})

stats class methods are:

method description
stats.isFile () If the file returns true, otherwise it returns false.
stats.isDirectory () If the directory returns true, otherwise it returns false.
stats.isBlockDevice () If the block device returns true, otherwise it returns false.
stats.isCharacterDevice () If the device is a character returns true, otherwise returns false.
stats.isSymbolicLink () If it is a soft link to return true, otherwise it returns false.
stats.isFIFO () If the FIFO, returns true, otherwise it returns false. FIFO is a special type of UNIX command pipeline.
stats.isSocket () If Socket returns true, otherwise it returns false.

Examples

Next we create 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 above code is executed 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 to file

grammar

The following is written to the file in asynchronous mode syntax:

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

If the file exists, the method writes the contents will overwrite the old file contents.

parameter

Parameters as follows:

  • path - file path.

  • data - the data to be written to a file, which can be String (String) or Buffer (stream) object.

  • options - This parameter is an object that contains {encoding, mode, flag}.The default encoding is utf8, mode 0666, flag of 'w'

  • callback - callback function, the callback function contains only error messages arguments (err), returns when writing fails.

Examples

Next we create 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 above code is executed as follows:

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

Read the file

grammar

Here is the Asynchronous mode to read the file syntax:

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

This method uses a file descriptor to read the file.

parameter

Parameters as follows:

  • fd - back through fs.open () method of file descriptors.

  • buffer - the data is written to the buffer.

  • offset - offset write buffer is written.

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

  • position - beginning of the file is read, if the position is null, is read from the current position of the file pointer.

  • callback - callback function takes three arguments err, bytesRead, buffer, err error message, bytesRead indicates the number of bytes read, buffer the buffer object.

Examples

input.txt contents of the file:

本教程官网地址:www.w3big.com

Next we create 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 is executed as follows:

$ node file.js 
准备打开已存在的文件!
文件打开成功!
准备读取文件:
42  字节被读取
本教程官网地址:www.w3big.com

Close the file

grammar

Following is a closed file in asynchronous mode syntax:

fs.close(fd, callback)

This method uses a file descriptor to read the file.

parameter

Parameters as follows:

  • fd - back through fs.open () method of file descriptors.

  • callback - callback function has no parameters.

Examples

input.txt contents of the file:

本教程官网地址:www.w3big.com

Next we create 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 above code is executed as follows:

$ node file.js 
准备打开文件!
文件打开成功!
准备读取文件!
本教程官网地址:www.w3big.com
文件关闭成功

Intercept file

grammar

The following is the syntax asynchronous mode interception of file:

fs.ftruncate(fd, len, callback)

This method uses a file descriptor to read the file.

parameter

Parameters as follows:

  • fd - back through fs.open () method of file descriptors.

  • len - the length of the contents of the file intercepted.

  • callback - callback function has no parameters.

Examples

input.txt contents of the file:

site:www.w3big.com

Next we create 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 above code is executed as follows:

$ node file.js 
准备打开文件!
文件打开成功!
截取10字节后的文件内容。
文件截取成功。
读取相同的文件
site:www.r
文件关闭成功

Delete Files

grammar

The following is the syntax to delete the file:

fs.unlink(path, callback)

parameter

Parameters as follows:

  • path - file path.

  • callback - callback function has no parameters.

Examples

input.txt contents of the file:

site:www.w3big.com

Next we create 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 above code is executed as follows:

$ node file.js 
准备删除文件!
文件删除成功!

See input.txt file again and found no longer exists.


Create a directory

grammar

The following is the syntax to create the directory:

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

parameter

Parameters as follows:

  • path - file path.

  • mode - set the directory permissions, default is 0777.

  • callback - callback function has no parameters.

Examples

Next we create 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 above code is executed as follows:

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

Read directory

grammar

The following is the syntax to read the directory:

fs.readdir(path, callback)

parameter

Parameters as follows:

  • path - file path.

  • callback - callback function, the callback function takes two arguments err, files, err error message, files for the array list files in a directory.

Examples

Next we create 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 above code is executed as follows:

$ node file.js 
查看 /tmp 目录
input.out
output.out
test
test.txt

Remove directory

grammar

The following is the syntax to delete the directory:

fs.rmdir(path, callback)

parameter

Parameters as follows:

  • path - file path.

  • callback - callback function has no parameters.

Examples

Next we create 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 above code is executed as follows:

$ node file.js 
准备删除目录 /tmp/test
input.out
output.out
test
test.txt
读取 /tmp 目录
……

Reference file module method

The following is a list of files in the same manner Node.js modules:

No. Method & description
1 fs.rename (oldPath, newPath, callback)
Asynchronous rename (). Callback function has no parameters, but may throw.
2 fs.ftruncate (fd, len, callback)
Asynchronous ftruncate (). Callback function has no parameters, but may throw.
3 fs.ftruncateSync (fd, len)
Synchronization ftruncate ()
4 fs.truncate (path, len, callback)
Asynchronous truncate (). Callback function has no parameters, but may throw.
5 fs.truncateSync (path, len)
Synchronization truncate ()
6 fs.chown (path, uid, gid, callback)
Asynchronous chown (). Callback function has no parameters, but may throw.
7 fs.chownSync (path, uid, gid)
Synchronization chown ()
8 fs.fchown (fd, uid, gid, callback)
Asynchronous fchown (). Callback function has no parameters, but may throw.
9 fs.fchownSync (fd, uid, gid)
Synchronization fchown ()
10 fs.lchown (path, uid, gid, callback)
Asynchronous lchown (). Callback function has no parameters, but may throw.
11 fs.lchownSync (path, uid, gid)
Synchronization lchown ()
12 fs.chmod (path, mode, callback)
Asynchronous chmod (). Callback function has no parameters, but may throw.
13 fs.chmodSync (path, mode)
Synchronization chmod ().
14 fs.fchmod (fd, mode, callback)
Asynchronous fchmod (). Callback function has no parameters, but may throw.
15 fs.fchmodSync (fd, mode)
Synchronization fchmod ().
16 fs.lchmod (path, mode, callback)
Asynchronous lchmod (). Callback function has no parameters, but may throw. Only available on Mac OS X.
17 fs.lchmodSync (path, mode)
Synchronization lchmod ().
18 fs.stat (path, callback)
Asynchronous stat (). Callback function takes two arguments err, stats, stats are fs.Stats object.
19 fs.lstat (path, callback)
Asynchronous lstat (). Callback function takes two arguments err, stats, stats are fs.Stats object.
20 fs.fstat (fd, callback)
Asynchronous fstat (). Callback function takes two arguments err, stats, stats are fs.Stats object.
twenty one fs.statSync (path)
Synchronization stat (). Fs.Stats return an instance of.
twenty two fs.lstatSync (path)
Synchronization lstat (). Fs.Stats return an instance of.
twenty three fs.fstatSync (fd)
Synchronization fstat (). Fs.Stats return an instance of.
twenty four fs.link (srcpath, dstpath, callback)
Asynchronous link (). Callback function has no parameters, but may throw.
25 fs.linkSync (srcpath, dstpath)
Synchronization link ().
26 fs.symlink (srcpath, dstpath [, type ], callback)
Asynchronous symlink (). Callback function has no parameters, but may throw. type parameter can be set to 'dir', 'file', or 'junction' (default 'file').
27 fs.symlinkSync (srcpath, dstpath [, type ])
Synchronization symlink ().
28 fs.readlink (path, callback)
Asynchronous readlink (). Callback function takes two arguments err, linkString.
29 fs.realpath (path [, cache], callback)
Asynchronous realpath (). Callback function takes two arguments err, resolvedPath.
30 fs.realpathSync (path [, cache])
Synchronous realpath (). Returns the absolute path.
31 fs.unlink (path, callback)
Asynchronous unlink (). Callback function has no parameters, but may throw.
32 fs.unlinkSync (path)
Synchronization unlink ().
33 fs.rmdir (path, callback)
Asynchronous rmdir (). Callback function has no parameters, but may throw.
34 fs.rmdirSync (path)
Synchronization rmdir ().
35 fs.mkdir (path [, mode], callback)
S Asynchronous mkdir (2). Callback function has no parameters, but may throw. mode defaults to 0777.
36 fs.mkdirSync (path [, mode])
Synchronization mkdir ().
37 fs.readdir (path, callback)
Asynchronous readdir (3). Read the contents of the directory.
38 fs.readdirSync (path)
Synchronization readdir (). Returns an array of files list.
39 fs.close (fd, callback)
Asynchronous close (). Callback function has no parameters, but may throw.
40 fs.closeSync (fd)
Synchronization close ().
41 fs.open (path, flags [, mode ], callback)
Asynchronous open the file.
42 fs.openSync (path, flags [, mode ])
Synchronous version of fs.open ().
43 fs.utimes (path, atime, mtime, callback)
44 fs.utimesSync (path, atime, mtime)
Change file timestamps, file by file path specified.
45 fs.futimes (fd, atime, mtime, callback)
46 fs.futimesSync (fd, atime, mtime)
Change file timestamps, specified by the file descriptor.
47 fs.fsync (fd, callback)
Asynchronous fsync. Callback function has no parameters, but may throw.
48 fs.fsyncSync (fd)
Synchronization fsync.
49 fs.write (fd, buffer, offset, length [, position], callback)
The write buffer contents to the file specified by the file descriptor.
50 fs.write (fd, data [, position [, encoding]], callback)
Write to the file contents on file descriptor fd.
51 fs.writeSync (fd, buffer, offset, length [, position])
Synchronous version fs.write ().
52 fs.writeSync (fd, data [, position [, encoding]])
Synchronous version fs.write ().
53 fs.read (fd, buffer, offset, length, position, callback)
Read the contents of the documents on file descriptor fd.
54 fs.readSync (fd, buffer, offset, length, position)
Synchronous version fs.read.
55 fs.readFile (filename [, options], callback)
Asynchronous read the file contents.
56 fs.readFileSync (filename [, options])
57 fs.writeFile (filename, data [, options ], callback)
Asynchronous write to the file content.
58 fs.writeFileSync (filename, data [, options ])
Synchronous version fs.writeFile.
59 fs.appendFile (filename, data [, options ], callback)
Asynchronous additional file contents.
60 fs.appendFileSync (filename, data [, options ])
The synchronous version of fs.appendFile.
61 fs.watchFile (filename [, options], listener)
Modify the view of the file.
62 fs.unwatchFile (filename [, listener])
Stop viewing filename changes.
63 fs.watch (filename [, options] [ , listener])
Check filename changes, filename can be a file or directory. Back fs.FSWatcher object.
64 fs.exists (path, callback)
Detect a given path exists.
65 fs.existsSync (path)
Synchronous version fs.exists.
66 fs.access (path [, mode], callback)
Tests if the specified path of the user permissions.
67 fs.accessSync (path [, mode])
Synchronous version fs.access.
68 fs.createReadStream (path [, options])
Back ReadStream object.
69 fs.createWriteStream (path [, options])
Back WriteStream object.
70 fs.symlink (srcpath, dstpath [, type ], callback)
Asynchronous symlink (). Callback function has no parameters, but may throw.

For more details, check out the official website File Module Description: File the System .