首页 > 解决方案 > node.js 检查将新文件复制到磁盘是否已完成

问题描述

我正在尝试使用 electron / node.js 编写一个系留射击应用程序。

相机和计算机之间的通信由相机附带的软件管理。新的图片直接复制到我的本地硬盘。之后,我的应用程序应该尽快显示新图片。

我为我的新照片到达的目录设置了一个 chokidar watcher。不幸的是

awaitWriteFinish: {stabilityThreshold: 500, pollInterval: 50}

chokidar 选项的作用非常缓慢,有时会过早触发添加事件。

我的想法是在观察者(没有 awaitWriteFinish 选项)触发事件后编写我自己的轮询机制。

我尝试使用 fs.stats 进行轮询,但 fs.stats 无法识别当前文件大小,而是识别总文件大小。

是否有一种简单的 node.js / javascript / jquery 方法来检测新文件是否完全写入磁盘?

任何帮助表示赞赏。

标签: javascriptnode.jspolling

解决方案


我相信你可以观察目录的变化。也许先扫描它以获得文件列表。例如,如果文件您在 Windows 上并且文件保存在 C:\temp

const fs = require('fs')
const saveDir = 'C\\temp'

let currentFiles = [];

// Read all cuurent files in directory
fs.readdirSync(saveDir, (error, files) =>
{
  currentFiles = files;
});


fs.watch(saveDir, (eventType, fileName) => 
{
  if (currentFiles.includes(fileName))
  {
    return;
  }
  
  // Handle rename event
  
  // Handle change event
  
});

更多信息在这里:

https://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener


推荐阅读