目录"/>
使用nodejs观看目录
我正在尝试监视 ftp 服务器中新添加的文件,该服务器的目录映射到运行节点应用程序的服务器上的驱动器。问题是它没有为通过 ftp 添加的文件注册任何事件;当通过节点应用程序修改或创建文件时,它们会被很好地拾取。
我目前正在使用 chokidar 来监视目录并使用以下简单代码记录任何事件:
const watcher = chokidar.watch('./myDir', {
persistent: true,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100
}
});
watcher
.on('add', path => console.log(`File ${path} has been added`))
.on('change', path => console.log(`File ${path} has been changed`));
我添加了
awaitWriteFinish
选项来尝试查看当文件从 ftp 传输完成时是否会注册,但没有任何喜悦。
有什么建议吗?
回答如下:您可以使用本机模块观看目录
fs
:
const fs = require('fs');
const folderPath = './test';
const pollInterval = 300;
let folderItems = {};
setInterval(() => {
fs.readdirSync(folderPath)
.forEach((file) => {
let path = `${folderPath}/${file}`;
let lastModification = fs.statSync(path).mtimeMs;
if (!folderItems[file]) {
folderItems[file] = lastModification;
console.log(`File ${path} has been added`);
} else if (folderItems[file] !== lastModification) {
folderItems[file] = lastModification;
console.log(`File ${path} has been changed`);
}
});
}, pollInterval);
但是上面的例子不会查看子文件夹中的文件。观看所有子文件夹的另一种方法是通过节点
find
函数使用 unix
child_process.exec
。
const fs = require('fs');
const {execSync} = require('child_process');
const folderPath = './test';
const pollInterval = 500;
let folderItems = {};
setInterval(() => {
let fileList = execSync(`find ${folderPath}`).toString().split('\n');
for (let file of fileList) {
if (file.length < 1) continue;
let lastModification = fs.statSync(file).mtimeMs;
if (!folderItems[file]) {
folderItems[file] = lastModification;
console.log(`File ${file} has been added`);
} else if (folderItems[file] !== lastModification) {
folderItems[file] = lastModification;
console.log(`File ${file} has been changed`);
}
}
}, pollInterval);
更多推荐
使用nodejs观看目录
发布评论