XMen
XMen

Reputation: 30258

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.

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 .

Upvotes: 0

Views: 240

Answers (1)

Alex Turpin
Alex Turpin

Reputation: 47776

If you want to know whether there was an error loading the file, check if err is not 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:

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");
});

Upvotes: 1

Related Questions