2017-07-06 65 views
0

我試圖監視任何新添加的文件到ftp服務器,該服務器將目錄映射到正在運行節點應用程序的服務器上的驅動器。問題是它不會爲通過ftp添加的文件註冊任何事件;當通過節點應用程序修改或創建文件時,它們可以很好地拾取。使用nodejs監視目錄 - 未註冊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傳輸完成,但沒有喜悅。

有什麼建議嗎?

+0

您是否嘗試過使用本地API來做到這一點? https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_watch_filename_options_listener –

+0

是的,結果相同。我已經讀過,chokadir在註冊fs.watch錯過的活動時更加可靠。 – user1565766

回答

0

您可以使用本機模塊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); 

但在子文件夾上面的例子也不會看的文件。另一種觀察所有子文件夾的方法是使用unix find通過節點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); 
+0

如果文件直接位於/ test目錄中,這是一個很好的解決方案。但是,我需要檢查/ test/xx/xx中的文件。 – user1565766

+0

增加了一個使用unix'fiind'來觀察所有子文件夾的例子 – gnuns