marwari
marwari

Reputation: 191

TypeError: Cannot read property 'length' of undefined in Node.js

I'm trying to create a server but it is throwing me an error in console

$ node server1185
Server listening at 1185

C:\Users\Bharat\Desktop\Nodejs\server1185.js:9

res.writeHead(200,{'Content-Type':'text/html', 'Content-Length': data.length
                                                                  ^

TypeError: Cannot read property 'length' of undefined
    at ReadFileContext.callback (C:\Users\Bharat\Desktop\Nodejs\server1185.js:9:
71)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)

My Node.js code is following

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res){
displayForm(res);
});

function displayForm(res){
fs.readFile('form.html', function(err,data){
res.writeHead(200,{'Content-Type':'text/html', 'Content-Length': data.length
});
res.write(data);
res.end();
});
}
server.listen(1185);
console.log('Server listening at 1185');
It is throwing an error in data.length, an explanation will be appreciated.

Upvotes: 1

Views: 2293

Answers (1)

M14
M14

Reputation: 1810

You have to handle the err object properly Log both err and data object. You will understand the problem

 if(err)
    {
        console.log(err)
    }
    else
  {
   res.writeHead(200,{'Content-Type':'text/html', 'Content-Length': data.length
 }

Upvotes: 1

Related Questions