要在node.js中打开或关闭特定文件

时间:2017-08-21 14:20:53

标签: javascript node.js lsof

我需要在node.js中检查特定文件是打开还是关闭。如果某个特定文件已关闭,我们将重命名该文件。当我在终端(Mac)上运行以下命令时,它给出了正确的结果。

lsof +D /Users/amitraj/Documents/traces

但是当我在node.js中运行上面的命令时,它给了我错误。以下是源代码:

var child =
    cp.spawn('lsof +D /Users/amitraj/Documents/traces', []);

child.stdout.on('data', function(chunk) {
    chunk.toString().split('\n').forEach(function(line) {
        console.log(line);
    });
});

child.stdout.on('end', function(chunk) {
    "use strict";
    console.log("end");
});

child.on('error', function(e) {
    "use strict";
    console.log(e);
});

我收到以下错误:

{ Error: spawn lsof +D /Users/amitraj/Documents/traces/ ENOENT
    at exports._errnoException (util.js:1018:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
    at onErrorNT (internal/child_process.js:367:16)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    at Module.runMain (module.js:606:11)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn lsof +D /Users/amitraj/Documents/traces/',
  path: 'lsof +D /Users/amitraj/Documents/traces/',
  spawnargs: [] }
end

我也尝试了以下代码,但仍然出现错误:

let cmd = "lsof +D /Users/amitraj/Documents/traces";

var result = require('child_process').execSync(cmd);

cp.exec(cmd, (error, stdout, stderr) => {
    //do whatever here
    if (error) {
        console.log(`error: `);
        console.log(error);
    }
    if (stdout) {
        console.log(`output : `);
        console.log(stdout);
    }
    if (stderr) {
        console.log(`stderr: `);
        console.log(stderr);
    }

});

错误:

Error: Command failed: lsof +D /Users/amitraj/Documents/traces

at checkExecSyncError (child_process.js:481:13)
at Object.execSync (child_process.js:521:13)
at Object.<anonymous> (/Users/amitraj/Downloads/notification/cs/cs.js:465:39)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)

0 个答案:

没有答案