10

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

jLynx
  • 1,111
  • 3
  • 20
  • 36
  • 2
    I think `sendFile` is an [ExpressJS](http://expressjs.com/) response method. You'll need to install and use Express in order to use it. – Andy Dec 10 '15 at 05:29

10 Answers10

29

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.

lift-it-luke
  • 407
  • 1
  • 6
  • 11
14

sendFile only in Express module.

Try this code

 var express = require('express');
 var app = express();
 app.get('/', function(req, res) {
     res.sendFile('path-to-file');
 });
 app.listen(PORT);
Toanalien
  • 659
  • 1
  • 7
  • 15
8

Piggybacking on Toanalien's (correct) answer, you could accomplish the same by:

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

http.createServer(function (req, res) {
  // maybe test for existence here using fs.stat

  res.writeHead(200, {"Content-Type": "text/html"});

  fs.createReadStream(path.resolve(__dirname, 'test.html')) 
    .pipe(res);

}).listen(process.env.PORT || '3000'); // provide a default  

See http.ServerResponse and fs.createReadStream.

ugo
  • 2,705
  • 2
  • 30
  • 34
Fissure King
  • 1,250
  • 7
  • 17
5

I had the same problem, this worked for me. Hope it will work.

 function(req,res){};
  • first argument should be "req" *
serge
  • 13,940
  • 35
  • 121
  • 205
Mehran Ahemad
  • 61
  • 1
  • 3
2

The answer above is correct, I'm just adding working example with no express.js but route dispatcher.

var http = require('http');                                                                         
var Router = require('routes');                                                                                                                                                   
var router = Router();                                                                                 
var fs = require('fs')                                                                         

router.addRoute("GET /test", (req, res, params) => {  
    let file = __dirname + '/views/test.html'                                                     
    res.writeHead(200, {"Content-Type": "text/html"});                                                 
    fs.createReadStream(file).pipe(res);                        
});                                                                                                    

var server = http.createServer((req, res) => {                                                   
 var match = router.match(req.method + ' ' + req.url);                                                 
 if (match) match.fn(req, res, match.params);                                                          
 else {                                                                                                
  res.statusCode = 404;                                                                                
  res.end('not found\n');                                                                              
 }                                                                                                     
}).listen(process.env.PORT || 3000);

calling endpoint /test will return the views/test.html.

 package.json is,

{                                                                                                                                                                                 
  "name": "node-app",                                                                                  
  "version": "1.0.0",                                                                                  
  "description": "node api",                                                                           
  "main": "server.js",                                                                                 
  "scripts": {                                                                                         
    "test": "echo \"Error: no test specified\" && exit 1"                                              
  },                                                                                                   
  "author": "prayagupd",                                                                               
  "license": "ISC",                                                                                    
  "dependencies": {
    "request": "^2.75.0",                                                                              
    "request-promise": "^4.1.1",                                                                       
    "routes": "^2.1.0"                                                                                 
  }                                                                                                    
}
prayagupa
  • 30,204
  • 14
  • 155
  • 192
1

Try this homies

const index = path.resolve(root + '/index.html');
const http = require('http');

const server = http.createServer((req, res) => {
   res.setHeader('Content-Type', 'text/html');
   fs.createReadStream(index).pipe(res);
});
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
1
app.get("/", function(req,res){
    res.sendFile(__dirname + "/html filename with .html extension");
});

Checkout that in a function first parameter must be req and then res, make sure that you have done the same, because sometimes we get an error just because of some small mistakes.

This is my personal experience, I have tried all the solutions, but when I checked my code, then I observed that i have written res as a first argument and req as a second argument.

matthias_h
  • 11,356
  • 9
  • 22
  • 40
0

install express in your system using following in your terminal [ubuntu]

npm install express
Manna
  • 27
  • 4
0

In my case, it happened because the function was requiring two arguments but I assigned 3 like this:

app.use(function notFoundHandler(err, req, res) {
    res.sendFile('404.html');
})

Then I removed the 'err' argument and it worked perfectly. like this:

app.use(function notFoundHandler(req, res) {
    res.sendFile('404.html');
})
borchvm
  • 3,533
  • 16
  • 44
  • 45
naeem1098
  • 123
  • 2
  • 9
-1

Well I've done some testing and the major issue is that the callback has to have two arguments (req,res)=>{}, trying to implement the code without this throws errors, and of course express must be installed as dependency. The names u give the parameters aren't of major importance but if u must use just one parameter , that would be interpreted as req

  • This answer is quite misleading and confusing. It's not required to have two arguments, and doing so will not cause any errors. Parameters in JavaScript are positional (as opposed to named). This means that the request will always be the first parameter, no matter the name, and the second will be the response, no matter the name. If you only put one parameter, that parameter will simply just be the request and you won't get a response object. This is what I think you're hinting at, but the answer is very unclear. Please edit your answer so other readers can get a better idea of what you mean. – Jesse Sep 01 '22 at 23:25