Watching for file changes on complete file transfer

烂漫一生 提交于 2019-12-08 01:04:43

问题


I have a simple node script that looks for a file changes and copies file to the remote server using ssh.

fs.watch(filename,function(curr,prev){

//copy file to the remote server

});

However, since the file i'm watching is uploaded via ftp and for every chunk of data i recieve the file gets changed and the callback gets fired. Is there any way to look for changes only when the complete file has been transfered?

Thanks in advance.


回答1:


I know this is an old question but for anyone else in the same situation there is now the below module:

https://www.npmjs.com/package/remote-file-watcher




回答2:


For Linux, you can probably get by with an inotify binding module and the IN_CLOSE_WRITE flag. That event will tell you when a process that previously opened the file for writing has now closed the file descriptor.




回答3:


I was in the same situation on a windows platform, and ended up doing this:

try {
    var nRetries = 10; 
    var retryTimeInterval = 500
    var currentRetry = 0;
    var pollFunction = function(){
    try{
        var rootFolder = path.dirname(require.main.filename);
        var completePathToFile = path.resolve(rootFolder, filePath);
        fs.readFileSync(path.resolve(rootFolder, filePath));

        // do stuff with file here
    }
    catch(e){
        if (currentRetry < nRetries) {
            currentRetry += 1;
            setTimeout(pollFunction, retryTimeInterval);
        } 
    };
pollFunction();

The file must be locked by the ftp server while being written to (So fs.readFileSync throws).

It is not very pretty, but I did not find any other way.



来源:https://stackoverflow.com/questions/21378627/watching-for-file-changes-on-complete-file-transfer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!