node文件系统

作者 新城 日期 2017-09-13
node文件系统

同步和异步 -
在fs模块的每一个方法都有同步和异步形式。异步方法需要最后一个参数为完成回调函数和回调函数的第一个参数是错误的。它优选使用异步方法来代替同步方法,前者从来不阻止程序的执行,作为第二使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var fs = require("fs");

// 异步
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});

// 同步
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

console.log("Program Ended");

输出结果

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

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

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

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

  • path - 这是文件名,包括路径字符串。
  • flags - 标志告知要打开的文件的行为。所有可能的值已经提及以下。
  • mode - 这将设置文件模式(许可和粘性位),但前提是在创建该文件。它默认为0666,读取和写入。
  • callback - 这是回调函数得到两个参数(err, fd)。
    flags参数取值


获取文件信息

1
fs.stat(path, callback)

  • path - 这是有文件名,包括路径字符串。
  • callback - 这是回调函数得到两个参数(err, stats) ,其中统计数据是这是印在下面的例子中的fs.Stats类型的对象。


同步 文件写入读取

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

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

  • options - 第三个参数是一个对象,它将于{编码,模式,标志}。默认编码是UTF8,模式是八进制值0666和标志 ‘w’

关闭文件

1
fs.close(fd, callback)

删除文件

1
fs.unlink(path, callback)

创建目录

1
fs.mkdir(path,[mode], callback)
  • path - 这是包括路径的目录名。
  • mode - 这是要设置的目录权限。默认为0777。
  • callback - 这是回调函数

读取目录

1
fs.readdir(path, callback)

删除目录

1
fs.rmdir(path, callback)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 );
});
});
});

输出

{ Error: ENOENT: no such file or directory, rmdir ‘F:\tmp\test’
at Error (native)
errno: -4058,
code: ‘ENOENT’,
syscall: ‘rmdir’,
path: ‘F:\tmp\test’ }