English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Other

Node.js File System (FS)

Node.js FS

Node FS is an in-built module in Node.js that helps you handle files and perform operations on them.

NodeJs FS file operations

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")

Asynchronous and synchronous

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.

Instance

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.

Open file

Syntax

The syntax format for opening a file in asynchronous mode is as follows:

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

Parameters

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:

FlagDescription
rOpen 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.
rsRead files synchronously.
rs+Read and write files synchronously.
wOpen the file in write mode, if the file does not exist, it will be created.
wxSimilar 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.
aOpen the file in append mode, if the file does not exist, it will be created.
axSimilar 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.

Instance

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 
准备打开文件!
文件打开成功!

Get file information

Syntax

The following is the syntax format for getting file information asynchronously:

fs.stat(path, callback)

Parameters

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:

MethodDescription
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.

Instance

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

Writing to file

Syntax

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.

Parameters

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.

Instance

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

Read file

Syntax

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.

Parameters

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.

Instance

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

关闭文件

Syntax

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.

Parameters

Parameter usage instructions are as follows:

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

  • callback - Callback function, no parameters.

Instance

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
文件关闭成功

截取文件

Syntax

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.

Parameters

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.

Instance

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
文件关闭成功

删除文件

Syntax

以下为删除文件的语法格式:

fs.unlink(path, callback)

Parameters

Parameter usage instructions are as follows:

  • path - File path.

  • callback - Callback function, no parameters.

Instance

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 文件,发现已经不存在了。

创建目录

Syntax

以下为创建目录的语法格式:

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

Parameters

Parameter usage instructions are as follows:

  • path - File path.

  • options 参数可以是:

    • recursive - 是否以递归的方式创建目录,默认为 false。

    • mode - 设置目录权限,默认为 0777.

  • callback - Callback function, no parameters.

Instance

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;
});

Read directory

Syntax

The following is the syntax format for reading a directory:

fs.readdir(path, callback)

Parameters

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.

Instance

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

Delete directory

Syntax

The following is the syntax format for deleting a directory:

fs.rmdir(path, callback)

Parameters

Parameter usage instructions are as follows:

  • path - File path.

  • callback - Callback function, no parameters.

Instance

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
……

File Module Method Reference Manual

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

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