dwerty
dwerty

Reputation: 17

Nodejs error: 'cannot read property isFile() of undefined'

I am trying to display a html file in browser using Nodejs. But when I run the code I got the following error:

cannot read property isFile() of undefined

This is the code that I am using:

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

var mimeTypes = {
    "html" : "text/html",
    "jpeg" : "image/jpeg",
    "jpg" : "image/jpg",
    "png" : "image/png",
    "js" : "text/javascript",
    "css" : "text/css"
};

var stats;


http.createServer(function(req, res) {
    var uri = url.parse(req.url).pathname;
    var fileName = path.join(process.cwd(),unescape(uri));
    console.log('Loading ' + uri);


    try {
        stats = fs.lstat(fileName);
    } catch(e) {
        res.writeHead(404, {'Content-type':'text/plain'});
        res.write('404 Not Found\n');
        res.end();
        return;
    }

    // Check if file/directory
    if (stats.isFile()) {
        var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
        res.writeHead(200, {'Content-type' : mimeType});

        var fileStream = fs.createReadStream(fileName);
        fileStream.pipe(res);
        return;
    } else if (stats.isDirectory()) {
        res.writeHead(302, {
            'Location' : 'index.html'
        });
        res.end();
    } else {
        res.writeHead(500, {
            'Content-type' : 'text/plain'
        });
        res.write('500 Internal Error\n');
        res.end();
    }
}).listen(3000);

The error I am getting is near stats.isFile(). I tried to resolve the error. But it is not working for me. I need some suggestions on resolving this error.

Upvotes: 1

Views: 2937

Answers (2)

palash kulshreshtha
palash kulshreshtha

Reputation: 587

You are using wrong function. You should use:

stat=fs.lstatSync("your file")

Then your code should work.

fs.lstat("your file",function (err,stats){})

is an async function which expects callback. Take a look at the documentation here.

Upvotes: 0

curtwphillips
curtwphillips

Reputation: 5811

The variable stats gets set to undefined, without throwing an error. This happens because fs.lstat(fileName) returns undefined.

Before the if statements, or perhaps instead of the try catch block, you may want to do something like:

if (!stats) {
    res.writeHead(404, {'Content-type':'text/plain'});
    res.write('404 Not Found\n');
    res.end();
    return;
}

Upvotes: 1

Related Questions