[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)
117 Answers
The error is pretty clear, you need to specify an absolute (instead of relative) path and/or set root
in the config object for res.sendFile()
. Examples:
// assuming index.html is in the same directory as this script res.sendFile(__dirname + '/index.html');
or specify a root (which is used as the base path for the first argument to res.sendFile()
:
res.sendFile('index.html', { root: __dirname });
Specifying the root
path is more useful when you're passing a user-generated file path which could potentially contain malformed/malicious parts like ..
(e.g. ../../../../../../etc/passwd
). Setting the root
path prevents such malicious paths from being used to access files outside of that base path.
in .mjs files we for now don't have __dirname
hence
res.sendFile('index.html', { root: '.' })
3Try adding root path.
app.get('/', function(req, res) { res.sendFile('index.html', { root: __dirname }); });
0I used the code below and tried to show the sitemap.xml file
router.get('/sitemap.xml', function (req, res) { res.sendFile('sitemap.xml', { root: '.' }); });
1If 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')); });
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')));
It will redirects to index.html on localhost:8080 call.
app.get('/',function(req,res){ res.sendFile('index.html', { root: __dirname }); });
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 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")); });
Unfortunately in ES6, to get access to absolute path __dir_name
you will have to enter the following code everywhere:
import { dirname } from 'path'; import { fileURLToPath } from 'url' const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);
Or create a path.js
with the functions you want to use:
import { join, dirname } from 'path'; import { fileURLToPath } from 'url' const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); export { __dirname, join };
And import before using: import { join, __dirname } from './path.js';
Something that happened to me is that when using res.sendFile, I got a console message similar to: "path must be absolute or specific root to res.sendFile" because the local variable __dirname returns a relative path, instead use procces.cwd() to locate my app root and pass the folder where my templates are hosted. Maybe it is not the best option but for the moment it works for me:
import process from "process" import path from "path"; let templates = path.join(process.cwd(), "src\\public\\templates") app.get("/", function(req, res){ res.sendFile('403.html', {root: templates}); });
Just Do it it will solve your problem.
res.sendFile('index.html', {root: '.'})
Explanation:
=> This code will send the "index.html" file located in the root directory of the server as the response when the request will made.
=> The first argument is the file path relative to the root directory, in this case, "index.html". The second argument, { root: '.' }, specifies the root directory from which the file should be served.
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 did this and now my app is working properly,
res.sendFile('your drive://your_subfolders//file.html');
1You might consider using double slashes on your directory e.g
app.get('/',(req,res)=>{ res.sendFile('C:\\Users\\DOREEN\\Desktop\\Fitness Finder' + '/index.html') })
0ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoaW9oZ26Dcn2Op6adnV2fwG7A2KmcnqqipL9uvMCtn2alpajBbq7EZpibq5%2BhwrWxjKipZqugmrCqsthmqainpGLBsHnRnqpmq5Wjsae1y55kn5mZobKl