node.js文件操作系统实例详解

2020-06-17 05:35:11易采站长站整理

var path = require('path');
var getFilesInDir = function(dir){
var results = [ path.resolve(dir) ];
var files = fs.readdirSync(dir, 'utf8');
files.forEach(function(file){
file = path.resolve(dir, file);
var stats = fs.statSync(file);
if(stats.isFile()){
results.push(file);
}else if(stats.isDirectory()){
results = results.concat( getFilesInDir(file) );
}
});
return results;
};
var files = getFilesInDir('../');
console.log(files);

异步版本:(TODO)

文件重命名


// fs.rename(oldPath, newPath, callback)
var fs = require('fs');
fs.rename('./hello', './world', function(err){
if(err) throw err;
console.log('重命名成功');
});
fs.renameSync(oldPath, newPath)
var fs = require('fs');
fs.renameSync('./world', './hello');

监听文件修改

fs.watch()比fs.watchFile()高效很多(why)

fs.watchFile()

实现原理:轮询。每隔一段时间检查文件是否发生变化。所以在不同平台上表现基本是一致的。


var fs = require('fs');
var options = {
persistent: true, // 默认就是true
interval: 2000 // 多久检查一次
};
// curr, prev 是被监听文件的状态, fs.Stat实例
// 可以通过 fs.unwatch() 移除监听
fs.watchFile('./fileForWatch.txt', options, function(curr, prev){
console.log('修改时间为: ' + curr.mtime);
});

修改fileForWatch.txt,可以看到控制台下打印出日志

/usr/local/bin/node watchFile.js
修改时间为: Sat Jul 16 2016 19:03:57 GMT+0800 (CST)
修改时间为: Sat Jul 16 2016 19:04:05 GMT+0800 (CST)

为啥子?莫非单纯访问文件也会触发回调?

If you want to be notified when the file was modified, not just accessed, you need to compare curr.mtime and prev.mtime.

在 v0.10 之后的改动。如果监听的文件不存在,会怎么处理。如下

Note: when an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, blksize and blocks fields will be undefined, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.

fs.watch()

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

这接口非常不靠谱(当前测试用的v6.1.0),参考 https://github.com/nodejs/node/issues/7420

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

注意:fs.watch()这个接口并不是在所有的平台行为都一致,并且在某些情况下是不可用的。recursive这个选项只在mac、windows下可用。