0

I am new to node js express. I am trying to open a html page at location D:\d3 project\index12.htm. The app.js is at location D:\d3 project\project_part1\project_part1\app.js

app.use(express.static('D:\d3 project')); 
app.get('/', function (req, res) {
res.sendFile('D:/d3 project' + '/'+'index12.html'); 
});
var server = app.listen(3001, '0.0.0.0', function () {
console.log('Listening on port %d', server.address().port);
});

I am getting this error

TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (D:\d3 project\project_part1\project_part1\node_modules\express\lib\response.js:403:11)
at D:\d3 project\project_part1\project_part1\app.js:10:9
at Layer.handle [as handle_request] (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\layer.js:95:5)
at next (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\layer.js:95:5)
at D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\index.js:277:22
at Function.process_params (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\index.js:330:12)
at next (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\index.js:271:10)
at SendStream.error (D:\d3 project\project_part1\project_part1\node_modules\express\node_modules\serve-static\index.js:120:7)

I suppose I am giving the absolute path and not the relative path..

Solution: just changed the code to

 res.sendFile(path.join(__dirname + '/../../index12.html'));

and add

var path = require('path');
Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55
  • Following link http://stackoverflow.com/questions/26079611/node-js-typeerror-path-must-be-absolute-or-specify-root-to-res-sendfile-failed will help you. – Fanjo Lama May 30 '16 at 05:52
  • Thank you. But i do not want to link it through _dirname.. is there any option of using ../ to go back 2 folders? – Suchitra Iyer May 30 '16 at 05:57
  • you should always link it through __dirname. Given that when you deploy your code on some other machine, the rest of the folder structure would not be under your control, while your application's folder structure would remain under your control. – Rahul Nanwani May 30 '16 at 06:27
  • Also, you are using path.join incorrectly. You could write `res.sendFile(path.join(__dirname, '../../index12.html'))` and let `path` module take care of leading and trailing slashes. – Rahul Nanwani May 30 '16 at 06:28
  • alright.. tried dat....thank u.. – Suchitra Iyer May 30 '16 at 06:33

0 Answers0