Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js File System

Node.js File System

Node.js's file system module (fs module) provides a rich set of APIs for reading, writing, deleting files, and performing other file system operations.

The fs module supports both synchronous and asynchronous methods, allowing developers to choose the appropriate approach for handling file operations based on specific needs.

Import the fs module

First, you need to import the fs module:


var fs = require("fs")

Asynchronous and Synchronous

The methods in the Node.js file system (fs module) all have asynchronous and synchronous versions; for example, the function for reading file content has the asynchronous fs.readFile() and the synchronous fs.readFileSync().

The last parameter of an asynchronous method function is a callback function, and the first parameter of the callback contains the error information (error).

It is recommended to use asynchronous methods; compared to synchronous methods, asynchronous methods have higher performance, are faster, and do not block.

Example

Create the example.txt file with the following content:


Runoob Tutorial官网地址:www.runoob.com
文件读取实例

Create the file.js file with the following code:

Example

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

(

'example.txt'

)

;

console.

log

(

"Synchronous read: "

data.

toString

(

)

)

;

console.

log

(

"Program execution complete."

)

;

The result of executing the above code is as follows:


$ node file.js 
同步读取: Runoob Tutorial官网地址:www.runoob.com
文件读取实例

程序执行完毕。
异步读取: Runoob Tutorial官网地址:www.runoob.com
文件读取实例

Writing to a File

Asynchronous file write:


fs.writeFile('example.txt', 'Hello, World!', (err) => {
    if (err) {
        console.error('Error writing file:', err);
        return;
    }
    console.log('File written successfully');
});

Synchronous file write:

try {
    fs.writeFileSync('example.txt', 'Hello, World!');
    console.log('File written successfully');
} catch (err) {
    console.error('Error writing file:', err);
}

Append content to file

Asynchronous append:

fs.appendFile('example.txt', '\nAppending some text', (err) => {
    if (err) {
        console.error('Error appending to file:', err);
        return;
    }
    console.log('Text appended successfully');
});

Synchronous append:

try {
    fs.appendFileSync('example.txt', '\nAppending some text');
    console.log('Text appended successfully');
} catch (err) {
    console.error('Error appending to file:', err);
}

Delete a file

Asynchronous file deletion:


fs.unlink('example.txt', (err) => {
    if (err) {
        console.error('Error deleting file:', err);
        return;
    }
    console.log('File deleted successfully');
});

Synchronous file deletion:


try {
    fs.unlinkSync('example.txt');
    console.log('File deleted successfully');
} catch (err) {
    console.error('Error deleting file:', err);
}

Create a directory

Asynchronous directory creation:


fs.mkdir('new_directory', (err) => {
    if (err) {
        console.error('Error creating directory:', err);
        return;
    }
    console.log('Directory created successfully');
});

Synchronous directory creation:

try {
    fs.mkdirSync('new_directory');
    console.log('Directory created successfully');
} catch (err) {
    console.error('Error creating directory:', err);
}

Read directory contents

Asynchronous directory content read:


fs.readdir('new_directory', (err, files) => {
    if (err) {
        console.error('Error reading directory:', err);
        return;
    }
    console.log('Directory contents:', files);
});

Synchronous directory content read:


try {
    const files = fs.readdirSync('new_directory');
    console.log('Directory contents:', files);
} catch (err) {
    console.error('Error reading directory:', err);
}

Check whether a file or directory exists

Asynchronous check:


fs.access('example.txt', fs.constants.F_OK, (err) => {
    if (err) {
        console.log('File does not exist');
    } else {
        console.log('File exists');
    }
});

Synchronous check:


try {
    fs.accessSync('example.txt', fs.constants.F_OK);
    console.log('File exists');
} catch (err) {
    console.log('File does not exist');
}

Advanced usage

1. File streams

File streams can be used to efficiently read and write large files without loading the entire file into memory at once.

Reading a file stream:

const fs = require('fs');

const readableStream = fs.createReadStream('large_file.txt', 'utf8');

readableStream.on('data', (chunk) => {
    console.log('Received chunk:', chunk);
});

readableStream.on('end', () => {
    console.log('No more data.');
});

Writing a file stream:

const fs = require('fs');

const writableStream = fs.createWriteStream('output.txt');

writableStream.write('Hello, ');
writableStream.write('World!\n');

writableStream.end();

writableStream.on('finish', () => {
    console.log('All writes are now complete.');
});

2. File system statistics

You can use fs.stat or fs.lstat to get statistics for a file or directory.

Get statistics asynchronously:


fs.stat('example.txt', (err, stats) => {
    if (err) {
        console.error('Error getting stats:', err);
        return;
    }
    console.log('Is file?', stats.isFile());
    console.log('Is directory?', stats.isDirectory());
    console.log('Size:', stats.size);
});

Get statistics synchronously:


try {
    const stats = fs.statSync('example.txt');
    console.log('Is file?', stats.isFile());
    console.log('Is directory?', stats.isDirectory());
    console.log('Size:', stats.size);
} catch (err) {
    console.error('Error getting stats:', err);
}

Next, let's take a detailed look at the Node.js file system methods.


Opening a File

Syntax

The following is the syntax for opening a file in asynchronous mode:


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

Parameters

The parameters are described below:

The flags parameter can have the following values:

Flag Description
r Open the file in read-only mode. The file must exist. If the file does not exist, an exception is thrown
r+ Open the file in read-write mode. The file must exist.
rs Open the file in read-only mode synchronously. A blocking operation, but may provide better stability on some operating systems.
rs+ Open the file in read-write mode synchronously. A blocking operation, but may provide better stability on some operating systems.
w Open the file in write-only mode. If the file does not exist, it is created; if it exists, it is truncated.
wx Similar to 'w', but fails if the path exists.
w+ Open the file in read-write mode. If the file does not exist, it is created; if it exists, it is truncated.
wx+ Similar to 'w+', but fails if the path exists.
a Open the file in append mode. If the file does not exist, it is created.
ax Similar to 'a', but fails if the path exists.
a+ Open the file in read and append mode. If the file does not exist, it is created.
ax+ Similar to 'a+', but fails if the path exists.

Example

Next we create the file.js file and open the input.txt file for reading and writing, with the following code:


var fs = require("fs");

// Asynchronously open file
console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
  console.log("文件打开成功!");     
});

The result of executing the above code is as follows:


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

Get file information

Syntax

The following is the syntax for getting file information in asynchronous mode:


fs.stat(path, callback)

Parameters

The parameters are described below:

After fs.stat(path) is executed, it returns an instance of the stats class to its callback function. The methods provided in the stats class can be used to determine the relevant attributes of a file. 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 include:

Method Description
stats.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 symbolic link, otherwise returns false.
stats.isFIFO() Returns true if it is a FIFO, otherwise returns false. A FIFO is a special type of command pipe in UNIX.
stats.isSocket() Returns true if it is a Socket, otherwise returns false.

Example

Next we create the file.js file with the following code:


var fs = require("fs");

console.log("准备打开文件!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }
   console.log(stats);
   console.log("读取文件信息成功!");
   
   // Detect file type
   console.log("是否为文件(isFile) ? " + stats.isFile());
   console.log("是否为目录(isDirectory) ? " + stats.isDirectory());    
});

The result of executing 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

Writing to a File

Syntax

The following is the syntax for writing a file in asynchronous mode:


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

writeFile opens the file directly in w mode by default, so if the file exists, the content written by this method will overwrite the old file content.

Parameters

The parameters are described below:

Example

Next we create the file.js file with the following code:


var fs = require("fs");

console.log("准备写入文件");
fs.writeFile('input.txt', '我是通 过fs.writeFile 写入文件的内容',  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 result of executing the above code is as follows:


$ node file.js 
准备写入文件
数据写入成功!
--------I am a separator-------------
读取写入的数据!
异步读取文件数据: 我是通 过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 below:

Example

The content of the input.txt file is:


Runoob Tutorial官网地址:www.runoob.com

Next we create the file.js file with the following code:


var fs = require("fs");
var buf = new Buffer.alloc(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 + "  字节被读取");
      
      // Only output the read bytes
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

The result of executing the above code is as follows:


$ node file.js 
准备打开已存在的文件!
文件打开成功!
Preparing to read file:
42  字节被读取
Runoob Tutorial官网地址:www.runoob.com

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 read the file.

Parameters

The parameters are described below:

Example

The content of the input.txt file is:


Runoob Tutorial官网地址:www.runoob.com

Next we create the file.js file with the following code:


var fs = require("fs");
var buf = new Buffer.alloc(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);
      }

      // Only output the read bytes
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }

      // Close file
      fs.close(fd, function(err){
         if (err){
            console.log(err);
         } 
         console.log("文件关闭成功");
      });
   });
});

The result of executing the above code is as follows:


$ node file.js 
准备打开文件!
文件打开成功!
准备读取文件!
Runoob Tutorial官网地址:www.runoob.com
文件关闭成功

Truncating a file

Syntax

The following is the syntax for truncating a file in asynchronous mode:


fs.ftruncate(fd, len, callback)

This method uses a file descriptor to read the file.

Parameters

The parameters are described below:

Example

The content of the input.txt file is:


site:www.runoob.com

Next we create the file.js file with the following code:


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

console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("文件打开成功!");
   console.log("截取10字节内的文件内容,超出部分将被去除。");
   
   // Capture file
   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);
         }

         // Only output the read bytes
         if(bytes > 0){
            console.log(buf.slice(0, bytes).toString());
         }

         // Close file
         fs.close(fd, function(err){
            if (err){
               console.log(err);
            } 
            console.log("文件关闭成功!");
         });
      });
   });
});

The result of executing the above code is as follows:


$ node file.js 
准备打开文件!
文件打开成功!
截取10字节内的文件内容,超出部分将被去除。
文件截取成功。
读取相同的文件
site:www.r
文件关闭成功

Delete a file

Syntax

The following is the syntax for deleting a file:


fs.unlink(path, callback)

Parameters

The parameters are described below:

Example

The content of the input.txt file is:


site:www.runoob.com

Next we create the file.js file with the following code:


var fs = require("fs");

console.log("准备删除文件!");
fs.unlink('input.txt', function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("文件删除成功!");
});

The result of executing the above code is as follows:


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

If you check the input.txt file again, you will find it no longer exists.


Create a directory

Syntax

The following is the syntax for creating a directory:


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

Parameters

The parameters are described below:

- ** recursive ** - whether to create directories recursively, defaults to false. - **mode** - set directory permissions, defaults to 0777.

Example

Next we create the file.js file with the following code:


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

The result of executing the above code is as follows:


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

You can add the recursive: true parameter, regardless of whether the directories /tmp and /tmp/a exist:

fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});

Reading a directory

Syntax

The following is the syntax for reading a directory:


fs.readdir(path, callback)

Parameters

The parameters are described below:

Example

Next we create the file.js file with the following code:


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 result of executing 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 for deleting a directory:


fs.rmdir(path, callback)

Parameters

The parameters are described below:

Example

Next we create the file.js file with the following code:


var fs = require("fs");
// Create an empty /tmp/test directory before execution
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 result of executing the above code is as follows:


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

File Module Methods Reference Manual

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

No. Method & Description
1 fs.rename(oldPath, newPath, callback)
Asynchronous rename(). The callback has no parameters, but may throw an exception.
2 fs.ftruncate(fd, len, callback)
Asynchronous ftruncate(). The callback has no parameters, but may throw an exception.
3 fs.ftruncateSync(fd, len)
Synchronous ftruncate()
4 fs.truncate(path, len, callback)
Asynchronous truncate(). The callback has no parameters, but may throw an exception.
5 fs.truncateSync(path, len)
Synchronous truncate()
6 fs.chown(path, uid, gid, callback)
Asynchronous chown(). The callback has no parameters, but may throw an exception.
7 fs.chownSync(path, uid, gid)
Synchronous chown()
8 fs.fchown(fd, uid, gid, callback)
Asynchronous fchown(). The callback has no parameters, but may throw an exception.
9 fs.fchownSync(fd, uid, gid)
Synchronous fchown()
10 fs.lchown(path, uid, gid, callback)
Asynchronous lchown(). The callback has no parameters, but may throw an exception.
11 fs.lchownSync(path, uid, gid)
Synchronous lchown()
12 fs.chmod(path, mode, callback)
Asynchronous chmod(). The callback has no parameters, but may throw an exception.
13 fs.chmodSync(path, mode)
Synchronous chmod().
14 fs.fchmod(fd, mode, callback)
Asynchronous fchmod(). The callback has no parameters, but may throw an exception.
15 fs.fchmodSync(fd, mode)
Synchronous fchmod().
16 fs.lchmod(path, mode, callback)
Asynchronous lchmod(). The callback has no parameters, but may throw an exception. Only available on Mac OS X.
17 fs.lchmodSync(path, mode)
Synchronous lchmod().
18 fs.stat(path, callback)
Asynchronous stat(). The callback has two parameters err, stats, where stats is an fs.Stats object.
19 fs.lstat(path, callback)
Asynchronous lstat(). The callback has two parameters err, stats, where stats is an fs.Stats object.
20 fs.fstat(fd, callback)
Asynchronous fstat(). The callback has two parameters err, stats, where stats is an fs.Stats object.
21 fs.statSync(path)
Synchronous stat(). Returns an instance of fs.Stats.
22 fs.lstatSync(path)
Synchronous lstat(). Returns an instance of fs.Stats.
23 fs.fstatSync(fd)
Synchronous fstat(). Returns an instance of fs.Stats.
24 fs.link(srcpath, dstpath, callback)
Asynchronous link(). The callback has no parameters, but may throw an exception.
25 fs.linkSync(srcpath, dstpath)
Synchronous link().
26 fs.symlink(srcpath, dstpath[, type], callback)
Asynchronous symlink(). The callback has no parameters, but may throw an exception. The type parameter can be set to 'dir', 'file', or 'junction' (defaults to 'file').
27 fs.symlinkSync(srcpath, dstpath[, type])
Synchronous symlink().
28 fs.readlink(path, callback)
Asynchronous readlink(). The callback has two parameters err, linkString.
29 fs.realpath(path[, cache], callback)
Asynchronous realpath(). The callback has two parameters err, resolvedPath.
30 fs.realpathSync(path[, cache])
Synchronous realpath(). Returns the absolute path.
31 fs.unlink(path, callback)
Asynchronous unlink(). The callback has no parameters, but may throw an exception.
32 fs.unlinkSync(path)
Synchronous unlink().
33 fs.rmdir(path, callback)
Asynchronous rmdir(). The callback has no parameters, but may throw an exception.
34 fs.rmdirSync(path)
Synchronous rmdir().
35 fs.mkdir(path[, mode], callback)
SAsynchronous mkdir(2). The callback has no parameters, but may throw an exception. Access permissions default to 0777.
36 fs.mkdirSync(path[, mode])
Synchronous mkdir().
37 fs.readdir(path, callback)
Asynchronous readdir(3). Reads the contents of a directory.
38 fs.readdirSync(path)
Synchronous readdir(). Returns an array list of files.
39 fs.close(fd, callback)
Asynchronous close(). The callback has no parameters, but may throw an exception.
40 fs.closeSync(fd)
Synchronous close().
41 fs.open(path, flags[, mode], callback)
Asynchronously open a 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)
Modify file timestamps, with the file specified by the given file path.
45 fs.futimes(fd, atime, mtime, callback)
 
46 fs.futimesSync(fd, atime, mtime)
Modify file timestamps, specified by a file descriptor.
47 fs.fsync(fd, callback)
Asynchronous fsync. The callback has no parameters, but may throw an exception.
48 fs.fsyncSync(fd)
Synchronous fsync.
49 fs.write(fd, buffer, offset, length[, position], callback)
Write buffer contents to the file specified by a file descriptor.
50 fs.write(fd, data[, position[, encoding]], callback)
Write file contents through the file descriptor fd.
51 fs.writeSync(fd, buffer, offset, length[, position])
Synchronous version of fs.write()
52 fs.writeSync(fd, data[, position[, encoding]])
Synchronous version of fs.write()
53 fs.read(fd, buffer, offset, length, position, callback)
Read file contents through the file descriptor fd.
54 fs.readSync(fd, buffer, offset, length, position)
Synchronous version of fs.read.
55 fs.readFile(filename[, options], callback)
Asynchronously read file contents.
56 fs.readFileSync(filename[, options])
57 fs.writeFile(filename, data[, options], callback)
Asynchronously write file contents.
58 fs.writeFileSync(filename, data[, options])
Synchronous version of fs.writeFile.
59 fs.appendFile(filename, data[, options], callback)
Asynchronously append file contents.
60 fs.appendFileSync(filename, data[, options])
The synchronous version of fs.appendFile.
61 fs.watchFile(filename[, options], listener)
Watch for file modifications.
62 fs.unwatchFile(filename[, listener])
Stop watching for modifications to filename.
63 fs.watch(filename[, options][, listener])
Watch for modifications to filename, which can be a file or a directory. Returns an fs.FSWatcher object.
64 fs.exists(path, callback)
Check whether a given path exists.
65 fs.existsSync(path)
Synchronous version of fs.exists.
66 fs.access(path[, mode], callback)
Test user permissions for the specified path.
67 fs.accessSync(path[, mode])
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)
Asynchronous symlink(). The callback has no parameters, but may throw an exception.

For more information, see the official documentation for the file module:File System。