使用nodejs观看目录

编程入门 行业动态 更新时间:2024-09-25 18:23:55

使用nodejs观看<a href=https://www.elefans.com/category/jswz/34/1771201.html style=目录"/>

使用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观看目录

本文发布于:2024-06-16 01:19:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目录   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!