[英]how to do validation of file exist with error handling
here is my function 这是我的功能
function loadscript(request, callback){
fs.readFile('scripts/'+request.filename, function(err, data){
callback(data);
});
}
how can i pass that if file not exist then it should reply error to call back . 如果文件不存在,我该如何传递它应该回复错误以进行回叫。
i tried fs.stat but one time it return the error.code to callback but second time when i call the function from the url of the server it gives the error. 我尝试了fs.stat,但是有一次它将error.code返回给回调,但是第二次当我从服务器的url调用函数时,它给出了错误。
The error it given with 它给出的错误
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)
what should i used to solve this . 我应该用什么来解决这个问题。
If you want to know whether there was an error loading the file, check if err
is not null
. 如果您想知道是否在加载文件时出错,请检查
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");
});
If you only want to do something if the file can't be found, you can check for err.code
being equal to ENOENT
: 如果您只想在找不到文件的情况下执行某些操作,则可以检查
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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.