Node.js - 文件系统

Node使用围绕标准POSIX函数的简单包装器实现文件I/O.节点文件系统(fs)模块可以使用以下语法导入 :

 
 var fs = require("fs")

同步与异步

fs模块中的每个方法都有同步和异步形式.异步方法将最后一个参数作为完成函数回调,将回调函数的第一个参数作为错误.最好使用异步方法而不是同步方法,因为前者在执行期间从不阻塞程序,而第二个方法则执行.

示例

创建一个名为 input.txt 的文本文件,其中包含以下内容 :

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

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

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Synchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Program Ended
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

本章的以下部分提供了一组关于主要文件I/O方法的好例子.

打开a文件

语法

以下是在异步模式下打开文件的方法的语法 :

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

参数

以下是所用参数的说明及减号;

  • 路径  : 去;这是包含路径的文件名的字符串.

  • flags : 标志指示要打开的文件的行为.所有可能的值都在下面提到.

  • 模式 : 它设置文件模式(权限和粘滞位),但仅限于创建文件的情况.它默认为0666,可读和可写.

  • 回调 : 这是回调函数,它获取两个参数(错误,fd).

标志

读/写操作的标志是 :

Sr.No.Flag&描述
1

r

打开文件进行阅读.如果文件不存在,则会发生异常.

2

r +

打开文件进行读写.如果文件不存在,则会发生异常.

3

rs

打开文件以便以同步模式读取.

4

rs +

打开文件进行读写,要求操作系统同步打开它.请参阅"rs"关于谨慎使用此事项的说明.

5

w

打开文件进行写作.创建文件(如果它不存在)或截断(如果存在).

6

wx

像'w'但是如果路径存在.

7

w +

打开文件进行读写.创建文件(如果它不存在)或截断(如果存在).

8

wx +

喜欢'w +'但是如果路径失败存在.

9

a

打开要追加的文件.如果文件不存在,则创建该文件.

10

ax

与'a'类似,但如果路径存在则失败.

11

a +

打开文件进行阅读和追加.如果文件不存在,则创建该文件.

12

ax +

与"a +"类似,但如果路径存在则失败.

示例

让我们创建一个名为 main的js文件. js 使用以下代码打开文件input.txt进行读写.

var fs = require("fs");

// Asynchronous - Opening File
console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");     
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to open file!
File opened successfully!

获取文件信息

语法

以下是语法获取文件信息的方法 :

 
 fs.stat(path,callback)

参数

以下是所用参数的说明及减号;

  • 路径 : 这是包含路径的文件名的字符串.

  • 回调 : 这是回调函数,它获取两个参数(err,stats),其中 stats 是fs.Stats类型的对象,在下面的例子中打印.

除了示例中下面打印的重要属性外, fs.Stats 类中有几种有用的方法可用于检查文件类型.这些方法在下表中给出.

Sr.No.Method&描述
1

stats.isFile()

如果是简单文件的文件类型,则返回true.

2

stats.isDirectory()

如果目录的文件类型,则返回true.

3

stats.isBlockDevice()

如果返回true,则返回true块设备的文件类型.

4

stats.isCharacterDevice()

如果是字符设备的文件类型,则返回true.

5

stats.isSymbolicLink()

如果符号链接的文件类型,则返回true.

6

stats.isFIFO()

如果FIFO的文件类型,则返回true.

7

stats.isSocket()

如果返回true,则返回true文件类型为asocket.

示例

让我们使用以下代码创建名为 main.js 的js文件;

var fs = require("fs");

console.log("Going to get file info!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
      return console.error(err);
   }
   console.log(stats);
   console.log("Got file info successfully!");
   
   // Check file type
   console.log("isFile ? " + stats.isFile());
   console.log("isDirectory ? " + stats.isDirectory());    
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to get file info!
{ 
   dev: 1792,
   mode: 33188,
   nlink: 1,
   uid: 48,
   gid: 48,
   rdev: 0,
   blksize: 4096,
   ino: 4318127,
   size: 97,
   blocks: 8,
   atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),
   mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),
   ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT) 
}
Got file info successfully!
isFile ? true
isDirectory ? false

编写文件

语法

以下是语法写入文件的方法之一 :

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

如果文件已存在,此方法将覆盖该文件.如果你想写入现有文件,那么你应该使用另一种方法.

参数

这是所用参数的描述 :

  • 路径 : 这是包含路径的文件名的字符串.

  • 数据 : 这是要写入文件的字符串或缓冲区.

  • options : 第三个参数是一个保持{encoding,mode,flag}的对象.默认情况下.编码为utf8,模式为八进制值0666.标志为'w'

  • 回调 : 这是一个回调函数,它获取一个参数错误,在出现任何写入错误时返回错误.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

var fs = require("fs");

console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
   if (err) {
      return console.error(err);
   }
   
   console.log("Data written successfully!");
   console.log("Let's read newly written data");
   
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!

读取文件

语法

以下是一个语法从文件中读取的方法 :

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

此方法将使用文件描述符来读取文件.如果你想直接使用文件名读取文件,那么你应该使用另一种方法.

参数

以下是对使用的参数 :

  • fd : 这是fs.open()返回的文件描述符.

  • 缓冲区 : 这是数据写入的缓冲区.

  • offset : 这是缓冲区中开始写入的偏移量.

  • 长度 : 这是一个整数,指定要读取的字节数.

  • position : 这是一个整数,指定从文件中开始读取的位置.如果position为null,则将从当前文件位置读取数据.

  • 回调 : 这是回调函数,它获取三个参数,(错误,bytesRead,缓冲区).

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

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

console.log("Going 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("Going to read the file");
   
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + " bytes read");
      
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to open an existing file
File opened successfully!
Going to read the file
97 bytes read
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

关闭文件

语法

以下是要关闭的语法打开的文件 :

 
 fs.close(fd,callback)

参数

以下是所用参数的说明及减号;

  • fd : 这是文件fs.open()方法返回的文件描述符.

  • 回调 : 这是回调函数除了可能的异常之外,没有给完成回调的参数.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

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

console.log("Going 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("Going to read the file");
   
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
      if (err) {
         console.log(err);
      }

      // Print only read bytes to avoid junk.
      if(bytes > 0) {
         console.log(buf.slice(0, bytes).toString());
      }

      // Close the opened file.
      fs.close(fd, function(err) {
         if (err) {
            console.log(err);
         } 
         console.log("File closed successfully.");
      });
   });
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to open an existing file
File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

File closed successfully.

截断文件

语法

以下是语法截断已打开文件的方法 :

 
 fs.ftruncate(fd,len,callback)

参数

以下是所用参数的说明及减号;

  • fd : 这是fs.open()返回的文件描述符.

  • len : 这是文件的长度,之后文件将被截断.

  • 回调 : 这是回调函数除了可能的异常之外,没有给完成回调的参数.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

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

console.log("Going 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("Going to truncate the file after 10 bytes");
   
   // Truncate the opened file.
   fs.ftruncate(fd, 10, function(err) {
      if (err) {
         console.log(err);
      } 
      console.log("File truncated successfully.");
      console.log("Going to read the same file"); 
      
      fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
         if (err) {
            console.log(err);
         }

         // Print only read bytes to avoid junk.
         if(bytes > 0) {
            console.log(buf.slice(0, bytes).toString());
         }

         // Close the opened file.
         fs.close(fd, function(err) {
            if (err) {
               console.log(err);
            } 
            console.log("File closed successfully.");
         });
      });
   });
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to open an existing file
File opened successfully!
Going to truncate the file after 10 bytes
File truncated successfully.
Going to read the same file
Tutorials 
File closed successfully.

删除文件

语法

以下是语法删除文件的方法 :

 
 fs.unlink(path,callback)

参数

以下是所用参数的说明及减号;

  • 路径 : 这是包含路径的文件名.

  • 回调 : 这是回调函数除了可能的异常之外,没有给完成回调的参数.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

var fs = require("fs");

console.log("Going to delete an existing file");
fs.unlink('input.txt', function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("File deleted successfully!");
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to delete an existing file
File deleted successfully!

创建目录

语法

以下是语法创建目录的方法 :

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

参数

以下是所用参数的说明及减号;

  • 路径 : 这是包含路径的目录名.

  • 模式 : 这是要设置的目录权限.默认为0777.

  • 回拨 : 这是回调函数除了可能的异常之外,没有给完成回调的参数.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

var fs = require("fs");

console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("Directory created successfully!");
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to create directory /tmp/test
Directory created successfully!!

读取目录

语法

以下是语法读取目录的方法 :

 
 fs.readdir(path,callback)

参数

以下是所用参数的说明及减号;

  • 路径 : 这是包含路径的目录名.

  • 回调 : 这是回调函数,它获取两个参数(错误,文件),其中files是目录中文件名的数组,不包括'.'和'..'.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

var fs = require("fs");

console.log("Going to read directory /tmp");
fs.readdir("/tmp/",function(err, files) {
   if (err) {
      return console.error(err);
   }
   files.forEach( function (file) {
      console.log( file );
   });
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test
test.txt

删除目录

语法

以下是删除目录的方法的语法 :

 
 fs.rmdir(path,callback)

参数

以下是所用参数的说明及减号;

  • 路径 : 这是包含路径的目录名.

  • 回调 : 这是回调函数除了可能的异常之外,没有给完成回调的参数.

示例

让我们创建一个名为 main.js 的js文件,其中包含以下代码 :

var fs = require("fs");

console.log("Going to delete directory /tmp/test");
fs.rmdir("/tmp/test",function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("Going to read directory /tmp");
   
   fs.readdir("/tmp/",function(err, files) {
      if (err) {
         return console.error(err);
      }
      files.forEach( function (file) {
         console.log( file );
      });
   });
});

现在运行main.js查看结果 :

 
 $ node main.js

验证输出.

Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test.txt

方法参考

Sr.No方法&描述
1

fs.rename(oldPath,newPath,callback)

异步重命名().除了可能的异常之外,没有给完成回调的参数.

2

fs.ftruncate(fd,len,callback)

异步ftruncate().除了可能的异常之外,没有给完成回调的参数.

3

fs.ftruncateSync(fd,len)

同步ftruncate ().

4

fs.truncate(path, len, callback)

异步truncate().除了可能的异常之外,没有给完成回调的参数.

5

fs.truncateSync(path,len)

同步截断().

6

fs.chown(路径,uid,gid,callback)

异步chown().除了可能的异常之外,没有给完成回调的参数.

7

fs.chownSync(path,uid,gid)

同步chown().

8

fs.fchown(fd,uid,gid,callback)

异步fchown().除了可能的异常之外,没有给完成回调的参数.

9

fs.fchownSync(fd,uid,gid)

同步fchown().

10

fs.lchown(path, uid, gid, callback)

异步lchown().除了可能的异常之外,没有给完成回调的参数.

11

fs.lchownSync(path,uid,gid)

同步lchown().

12

fs.chmod(path, mode, callback)

异步chmod().除了可能的异常之外,没有给完成回调的参数.

13

fs.chmodSync(path, mode)

同步chmod ().

14

fs.fchmod(fd,mode,callback)

异步fchmod().除了可能的异常之外,没有给完成回调的参数.

15

fs.fchmodSync(fd,mode)

同步fchmod ().

16

fs.lchmod(path, mode, callback)

异步lchmod().除了可能的异常之外,没有给完成回调的参数.仅适用于Mac OS X.

17

fs.lchmodSync(path, mode)

同步lchmod().

18

fs.stat(path, callback)

异步stat().回调得到两个参数(错误,统计),其中stats是fs.Stats对象.

19

fs.lstat(path, callback)

异步lstat().回调得到两个参数(错误,统计),其中stats是fs.Stats对象. lstat()与stat()相同,只是如果path是符号链接,则链接本身是stated ed,而不是它所引用的文件.

20

fs.fstat (fd,callback)

异步fstat().回调得到两个参数(错误,统计),其中stats是fs.Stats对象. fstat()与stat()相同,不同之处在于要由statd ed文件由文件描述符fd指定.

21

fs.statSync(path)

同步属性().返回fs.Stats的实例.

22

fs.lstatSync(path)

同步lstat().返回fs.Stats的实例.

23

fs.fstatSync(fd)

同步fstat().返回fs.Stats的实例.

24

fs.link(srcpath,dstpath,callback)

异步链接().除了可能的异常之外,没有给完成回调的参数.

25

fs.linkSync(srcpath,dstpath)

同步链接().

26

fs.symlink(srcpath,dstpath [,type],callback)

异步符号链接().除了可能的异常之外,没有给完成回调的参数. type参数可以设置为'dir','file'或'junction'(默认为'file'),并且仅在Windows上可用(在其他平台上被忽略).请注意,Windows联结点要求目标路径是绝对路径. When using ’junction’, the destination argument will automatically be normalized to absolute path.

27

fs.symlinkSync(srcpath, dstpath[, type])

Synchronous symlink().

28

fs.readlink(path, callback)

Asynchronous readlink(). The callback gets two arguments (err, linkString).

29

fs.realpath(path[, cache], callback)

Asynchronous realpath(). The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths. cache is an object literal of mapped paths that can be used to force a specific path resolution or avoid additional fs.stat calls for known real paths.

30

fs.realpathSync(path[, cache])

Synchronous realpath(). Returns the resolved path.

31

fs.unlink(path, callback)

Asynchronous unlink(). No arguments other than a possible exception are given to the completion callback.

32

fs.unlinkSync(path)

Synchronous unlink().

33

fs.rmdir(path, callback)

Asynchronous rmdir(). No arguments other than a possible exception are given to the completion callback.

34

fs.rmdirSync(path)

Synchronous rmdir().

35

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

Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.

36

fs.mkdirSync(path[, mode])

Synchronous mkdir().

37

fs.readdir(path, callback)

Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding ’.’ and ’..’.

38

fs.readdirSync(path)

Synchronous readdir(). Returns an array of filenames excluding ’.’ and ’..’.

39

fs.close(fd, callback)

Asynchronous close(). No arguments other than a possible exception are given to the completion callback.

40

fs.closeSync(fd)

Synchronous close().

41

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

Asynchronous file open.

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 of the file referenced by the supplied path.

45

fs.futimes (fd, atime, mtime, callback)

 

46

fs.futimesSync(fd, atime, mtime)

Change the file timestamps of a file referenced by the supplied file descriptor.

47

fs.fsync(fd, callback)

Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.

48

fs.fsyncSync(fd)

Synchronous fsync.

49

fs.write(fd, buffer, offset, length[, position], callback)

Write buffer to the file specified by fd.

50

fs.write(fd, data[, position[, encoding]], callback)

Write data to the file specified by fd. If data is not a Buffer instance then the value will be coerced to a string.

51

fs.writeSync(fd, buffer, offset, length[, position])

Synchronous versions of fs.write(). Returns the number of bytes written.

52

fs.writeSync(fd, data[, position[, encoding]])

Synchronous versions of fs.write(). Returns the number of bytes written.

53

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

Read data from the file specified by fd.

54

fs.readSync(fd, buffer, offset, length, position)

Synchronous version of fs.read. Returns the number of bytesRead.

55

fs.readFile(filename[, options], callback)

Asynchronously reads the entire contents of a file.

56

fs.readFileSync(filename[, options])

Synchronous version of fs.readFile. Returns the contents of the filename.

57

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

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

58

fs.writeFileSync(filename, data[, options])

The synchronous version of fs.writeFile.

59

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

Asynchronously append data to a file, creating the file if it does not exist. data can be a string or a buffer.

60

fs.appendFileSync(filename, data[, options])

The synchronous version of fs.appendFile.

61

fs.watchFile(filename[, options], listener)

Watch for changes on filename. The callback listener will be called each time the file is accessed.

62

fs.unwatchFile(filename[, listener])

Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed and you have effectively stopped watching filename.

63

fs.watch(filename[, options][, listener])

Watch for changes on filename, where filename is either a file or an directory. The returned object is an fs.FSWatcher.

64

fs.exists(path, callback)

Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false.

65

fs.existsSync(path)

Synchronous version of fs.exists.

66

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

Tests a user’s permissions for the file specified by path. mode is an optional integer that specifies the accessibility checks to be performed.

67

fs.accessSync(path[, mode])

Synchronous version of fs.access. It throws if any accessibility checks fail, and does nothing otherwise.

68

fs.createReadStream(path[, options])

Returns a new ReadStream object.

69

fs.createWriteStream(path[, options])

Returns a new WriteStream object.

70

fs.symlink(srcpath, dstpath[, type], callback)

Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The type argument can be set to ’dir’, ’file’, or ’junction’ (default is ’file’) and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using ’junction’, the destination argument will automatically be normalized to absolute path.