Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

res.sendFile is not a function Node.js

I am not able to send a HTML file using node.js

So first off this is the error I am getting

Application has thrown an uncaught exception and is terminated:
TypeError: res.sendFile is not a function
    at Server.<anonymous> (C:\Program Files\iisnode\www\test\app.js:4:6)
    at emitTwo (events.js:88:13)
    at Server.emit (events.js:173:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:529:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:89:23)

and my app.js code is

var http = require('http');

http.createServer(function (req, res) {
    res.sendFile('test.html', { root: __dirname });
}).listen(process.env.PORT);  

If I am missing something simple, I am sorry as this is the first node.js program I have made

like image 755
jLynx Avatar asked Dec 10 '15 05:12

jLynx


People also ask

What does res sendFile do?

The res. sendFile() function basically transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension.

What does sendFile return?

When sendfile() returns, this variable will be set to the offset of the byte following the last byte that was read. If offset is not NULL, then sendfile() does not modify the file offset of in_fd; otherwise the file offset is adjusted to reflect the number of bytes read from in_fd.

Is Res sendFile async?

res. sendFile() is asynchronous and it will end its own response if it is successful. So, when you call res.


1 Answers

This specific issue has already been answered, but it's worth mentioning that if you're using "express" version 3.x, the fix could be as easy as switching res.sendFile('path-to-file'); to res.sendfile('path-to-file');

This was the problem in my case. So you can either upgrade the express version (or) change the method name with lower case to fix this issue.

like image 168
lift-it-luke Avatar answered Oct 06 '22 01:10

lift-it-luke