[javascript] node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

[add] So my next problem is that when i try adding a new dependence (npm install --save socket.io). The JSON file is also valid. I get this error: Failed to parse json

npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR! 
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse 

So I've been trying to figure out why this error has been returning. All of the files (HTML,JSON,JS) are inside the same folder on my desktop. I'm using node.js and socket.io

This is my JS file:

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
  res.sendFile('index.html');
});

http.listen(3000,function(){
    console.log('listening on : 3000');
});

This is what is getting returned:

MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js 
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)

This question is related to javascript json node.js socket.io dependencies

The answer is


this configuration in app.js worked fine for me :

    //production mode
if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));
  app.get("*", (req, res) => {
    res.sendFile(path.join((__dirname + "/client/build/index.html")));

  });
}

//build mode
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname + "/client/public/index.html"));

});

You might consider using double slashes on your directory e.g

_x000D_
_x000D_
app.get('/',(req,res)=>{_x000D_
    res.sendFile('C:\\Users\\DOREEN\\Desktop\\Fitness Finder' + '/index.html')_x000D_
})
_x000D_
_x000D_
_x000D_


in .mjs files we for now don't have __dirname

hence

res.sendFile('index.html', { root: '.' })

It will redirects to index.html on localhost:8080 call.

app.get('/',function(req,res){
    res.sendFile('index.html', { root: __dirname });
});

Try adding root path.

app.get('/', function(req, res) {
    res.sendFile('index.html', { root: __dirname });
});

If you trust the path, path.resolve is an option:

var path = require('path');

// All other routes should redirect to the index.html
  app.route('/*')
    .get(function(req, res) {
      res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });

I solve this by using path variable. The sample code will look like below.

var path = require("path");

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html'));
})

This can be resolved in another way:

app.get("/", function(req, res){

    res.send(`${process.env.PWD}/index.html`)

});

process.env.PWD will prepend the working directory when the process was started.


I used the code below and tried to show the sitemap.xml file

router.get('/sitemap.xml', function (req, res) {
    res.sendFile('sitemap.xml', { root: '.' });
});

I did this and now my app is working properly,

res.sendFile('your drive://your_subfolders//file.html');

The error is pretty straightforward. Most likely the reason is that your index.html file is not in the root directory.

Or if it is in the root directory then the relative referencing is not working.

So you need to tell the server exact location of your file. This could be done by using dirname method in NodeJs. Just replace your code with this one:

 app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

Make sure that your add the slash "/" symbol before your homepage. Otherwise your path will become: rootDirectoryindex.html

Whereas you want it to be: rootDirectory/index.html


If you are working on Root Directory then you can use this approach

res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');

but if you are using Routes which is inside a folder lets say /Routes/someRoute.js then you will need to do something like this

const path = require("path");
...
route.get("/some_route", (req, res) => {
   res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});


In Typescript with relative path to the icon:

import path from 'path';

route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to socket.io

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 WebSockets and Apache proxy : how to configure mod_proxy_wstunnel? node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON] Socket.io + Node.js Cross-Origin Request Blocked Node.js: socket.io close client connection How to send a message to a particular client with socket.io Socket.IO handling disconnect event Get connection status on Socket.io client Which websocket library to use with Node.js? Maximum concurrent Socket.IO connections

Examples related to dependencies

Upgrading React version and it's dependencies by reading package.json How do I deal with installing peer dependencies in Angular CLI? RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'? Automatically create requirements.txt node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON] MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project npm install private github repositories by dependency in package.json Find unused npm packages in package.json Failed to load c++ bson extension Maven dependency update on commandline