2013-08-31 54 views
0

我剛開始學習節點。 這裏是我的問題,我得到了sample.js文件內容未定義,錯誤是錯誤:ENOENT,打開'C: Windows system32 hello.txt'

var fs=require("fs"); 
console.log("starting"); 
fs.readFile("hello.txt" , function(error,data){ 
    console.log("content is asdas " + data); 
}); 
console.log("executed"); 

,並與內容hello.txt的,他們都是我的桌面

hello 

,當我運行該管理員在PowerShell中或在cmd

C:\Windows\system32\ node C:\Users\X\Desktop\sample.js 

我得到

開始

執行

含量asdas不確定

當我登錄錯誤

var fs=require("fs"); 
console.log("starting"); 
fs.readFile("hello.txt" , function(error,data){ 
    console.log("content is asdas " + error); 
}); 
console.log("executed"); 

我得到

開始

執行

內容asdas錯誤:ENOENT,打開 'C:\ WINDOWS \ SYSTEM32 \ hello.txt的'

所以我想這個錯誤是節點正在尋找在system32下,不在桌面...?

謝謝!

+0

是............ –

回答

3

Node.js resolves relative paths from current working directory而不是從當前腳本/模塊。

If after using all from paths still no absolute path is found, the current working directory is used as well.

在這種情況下,這將是:

console.log(process.cwd()); 
// outputs: C:\Windows\system32\ 

要指定相對於腳本的路徑,你必須解決/加盟/等。路徑從自己__dirname

fs.readFile(__dirname + "/hello.txt", /* ... */); 
fs.readFile(path.join(__dirname, "hello.txt"), /* ... */); 
fs.readFile(path.resolve(__dirname, "hello.txt"), /* ... */); 
+0

現在我得到的內容是asdas空 變種FS =要求( 「FS」); console.log(「starting」); fs.readFile(__目錄名+ 「/ hello.txt的」,功能(錯誤,數據){ \t的console.log( 「內容爲asdas」 +誤差); }); console.log(「executed」); – LauroSkr

+0

@LauroSkr由於你記錄了'error','null'實際上是一件好事(讀取文件沒有錯誤)。嘗試換回日誌「數據」。而且,如果你得到類似'[object Buffer]'的東西,嘗試把它作爲一個單獨的參數傳遞,而不是自己連接它。 'console.log()'應該給它一個友好的格式。 –

相關問題