节点Js:测试以查看文件是否被其他进程锁定以进行编辑 [英] Node Js: Test to see if a file is locked for editing by another process

查看:671
本文介绍了节点Js:测试以查看文件是否被其他进程锁定以进行编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在NodeJs中编写一些代码,并希望检查该文件是否正在被另一个进程使用,如果它没有做任何事情,如果它没有被使用的话。

I am writing some code in NodeJs, and want to check to see if the file is in use by another process, if it is then do nothing, if it isn't in use do something.

fs.stats有点像,在这个瞬间文件大小是多少。并且不告诉我我目前是否正在使用其他流程。

fs.stats is kind of a, at this instant what is the file size. And doesn't tell me me if its currently in use from another process.

不确定还有什么可以尝试。

Not sure what else to try.

在尝试使用nodejs访问文件之前,判断文件当前是否被其他进程编辑锁定的最佳方法是什么?

What is the best way to tell if a file is currently locked for editing by another process, before trying to access the file using nodejs?

推荐答案

代码我在留下评论的一些指令后最终使用。

Code I ended up using after some instruction from the comments left.

var delInterval = setInterval(del(), 1000);

function del(){
    fs.open(filePath, 'r+', function(err, fd){
        if (err && err.code === 'EBUSY'){
            //do nothing till next loop
        } else if (err && err.code === 'ENOENT'){
            console.log(filePath, 'deleted');
            clearInterval(delInterval);
        } else {
            fs.close(fd, function(){
                fs.unlink(filePath, function(err){
                    if(err){
                    } else {
                    console.log(filePath, 'deleted');
                    clearInterval(delInterval);
                    }
                });
            });
        }
    });
}

这篇关于节点Js:测试以查看文件是否被其他进程锁定以进行编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆