2011-09-21 37 views
0

存在這裏是我的功能怎麼辦文件的驗證與錯誤處理

function loadscript(request, callback){ 

     fs.readFile('scripts/'+request.filename, function(err, data){ 
      callback(data); 
     }); 

} 

如何傳遞,如果不存在,那麼文件就應該回答錯誤回調。

我試過fs.stat,但有一次,它返回error.code回調,但第二次,當我從服務器的URL調用該函數的錯誤。它

TypeError: first argument must be a string, Array, or Buffer 
    at ServerResponse.write (http2.js:598:11) 
    at /home/reach121/basf/index.js:37:17 
    at /home/reach121/basf/index.js:81:3 
    at [object Object].<anonymous> (fs.js:81:5) 
    at [object Object].emit (events.js:67:17) 
    at Object.oncomplete (fs.js:948:12) 

我應該用什麼來解決這個問題給出

錯誤。

回答

1

如果您想知道加載文件是否出錯,請檢查err是不是null

var fs = require("fs"); 
fs.readFile("foo.js", function(err, data) { 
    if (err) { 
     console.log("error loading file"); 
     return; 
    } 

    console.log("file loaded"); 
}); 

如果你只想要做的事,如果該文件無法找到,您可以檢查err.code等於ENOENT

var fs = require("fs"); 
fs.readFile("foo.js", function(err, data) { 
    if (err && err.code == "ENOENT") { 
     console.log("file not found"); 
     return; 
    } 

    console.log("file found, but there might be other errors"); 
});