node的file system模块提供的api有同步和异步两种模式(大多数情况下都是用的异步方法,毕竟异步是node的特色,至于提供同步方法,可能应用程序复杂的时候有些场景使用同步会比较合适)。异步方法里回调函数的第一个参数往往是个err对象,最后一个参数是返回的操作结果。
node里面有很多模块,不少模块里面又有很多api,没必要短时间内一个个读完,因此只需要记住每个模块中最常用的一些api就好了。
*在使用同步模式的api时,error是即时抛出的,因此同步方法最好放在一个try{}catch{}块中。
*在使用异步模式的api时,如果一组任务之间是有先后次序的,要注意把下一个任务嵌在上一个任务的callback中。
*对文件读写时,可以使用相对路径,不过这个相对路径是相对于process.cwd()的。
Class: fs.ReadStream/fs.WriteStream:
.open()
.close()
.path
.bytesRead
--------------------------------------
Class: fs.Stats: fs.stat()
, fs.lstat()
and fs.fstat()的返回对象。
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
--------------------------------------
fs.access(path[, mode], callback):
用于检测用户对path中的文件/文件夹的权限;其中mode有下面四个值:
fs.constants.F_OK 对调用该方法的进程可见
fs.constants.R_OK 可读
fs.constants.W_OK 可写
fs.constants.X_OK 可执行
文档不推荐在fs.open(), fs.readFile() or fs.writeFile()方法前使用access方法,推荐直接使用open/read/write即可。access方法应该在不直接使用path路径下的文件的时候调用。
--------------------------------------
fs.appendFile(file, data[, options], callback):给文档追加数据
fs.appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
data:可以是字符|buffer
option:obj|string:为obj时候可设置的参数有:encoding
、mode
、flag;为string时则指定编码格式如‘utf-8’
-------------------------------------
fs.createReadStream(path[, options]):返回一个readStream实例
option是如下的默认对象,如果opton是字符串,则只是指定编码格式:
const defaults = {
flags: 'r',
encoding: null,
fd: null,
mode: 0o666,
autoClose: true
};
*如果指定了fd,则path参数会被忽略;open事件也不会被触发。Note that fd should be blocking; non-blocking fds should be passed to net.Socket.
-----------------------------
fs.createWriteStream(path[, options]):参考createReadStream
-----------------------------------
fs.exists(path, callback):判断路径中的文件/文件夹是否存在
fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
文档推荐使用.access()而不是.exists(),因为access的回调里有err参数,而exists只是返回一个布尔值。另外也不推荐在.open/write/read文件之前使用exists方法检测。
RECOMMENDED:
fs.open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
writeMyData(fd);
});
fs.open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
readMyData(fd);
});
后面还有好几十个方法。。。罢了罢了先停一下。