2017-07-07 158 views
0

我正在通過書Node.js the Right Way瞭解Node.js。我正在嘗試運行以下示例,以查看與.js文件位於同一目錄中的名爲target.txt的文件的更改。當看到文件被修改時,spawn ls ENOENT

"use strict"; 
const 
    fs = require('fs'), 
    spawn = require('child_process').spawn, 
    filename = process.argv[2]; 
if (!filename) { 
    throw Error("A file to watch must be specified!"); 
} 
fs.watch(filename, function() { 
    let ls = spawn('ls', ['-lh', filename]); 
    ls.stdout.pipe(process.stdout); 
}); 
console.log("Now watching " + filename + " for changes..."); 

我收到以下錯誤,當我更改文本文件並將其保存:

events.js:160 throw er; // Unhandled 'error' event ^

Error: spawn ls 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)

Node.js的版本:v6.11.0

IDE:Visual Studio代碼1.13.1

OS:Windows 10 64x

回答

0

在Windows上沒有ls,您應該使用dir來代替。

但是,這不是一個可執行文件。要運行.bat.cmd文件,您可以:

  • 菌種cmd.exe,並通過這些文件作爲參數:

    require('child_process').spawn('cmd', ['/c', 'dir']); 
    
  • 使用spawnshell選項設置爲true

    require('child_process').spawn('dir', [], { shell: true }); 
    
  • 使用exec代替spawn

    require('child_process').exec('dir', (err, stdout, stderr) => { ... }); 
    

欲瞭解更多關於這一點,看看this section in the official docs

編輯:

我不知道我理解你的評論質疑正確,但如果你去了第二個選項,例如,你的代碼看起來就像這樣:

... 

fs.watch(filename, function() { 
    let dir = spawn('dir', [filename], { shell: true }); 

    dir.stdout.pipe(process.stdout); 
}); 

... 

請記住,您可能需要稍微調整此代碼。我從內存中編寫所有這些,因爲我現在無法訪問Windows機器,所以我無法自己測試它。

+0

對不起,我改變了'require'行。你可以用'cmd'替換「watch」部分嗎?我得到的TypeError說「產卵不是一個功能」。謝謝。 – Disasterkid

+0

@Disasterkid我不確定我是否理解你的問題,但請看看答案上的編輯。 – Danziger

+0

這導致'let dir = spawn('dir',[filename],{shell:true}); ^ TypeError:在FSWatcher中,spawn不是函數 。 (events.js:191:00)處的emitTwo(events.js:106:13) ((在C:\ Users \ Pedram \ Documents \ Node \ hello \ watcher- spawn.js:10:15 ) ) 7) at FSEvent.FSWatcher._handle.onchange(fs。js:1426:12)' – Disasterkid