Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

330
Views
How to res.sendFile() a file that is in a different directory for Express.js webapp?

I have this inside controllers folder:

//controler.js
exports.serve_sitemap = (req, res) => {
  res.sendFile("../../sitemap.xml");
  // or
  // res.send(__dirname + "./sitemap.xml")
  // But neither of these work
};

This exported function is imported in a file inside the routes directory

const { serve_sitemap } = require('../controllers/indexer')

var router = require('express').Router()

router.get("/sitemap", serve_sitemap)

module.exports = router

Currently I am getting a 404 error when I try to get the sitmap at localhost:3000/sitemap

Folder Structure:
folder structure

Before, I had the same thing in index.js which is the entry point.

app.get("/sitemap", (req, res) => {
   res.sendFile(__dirname + "/sitemap.xml");
});

This was working perfectly, until I decided to restructure the project

  • How can I refer to the sitemap.xml file that is located in the root directory from a file that is in a sub-directory when using res.send()?
  • How can I get the absolute path to the root of the project directory, then I can append the file name to the path. This can solve the issse

I maybe missing something obvious. In that case, please help me out.

Any suggestion gratefully accepted. Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Why do you think that res.sendFile(__dirname + "./sitemap.xml") would work?

First of all __dirname + "./sitemap.xml" is not how paths should be concatenated you should use join instead especially if your second path starts with ./. And there is no file sitemap.xml in the directory of the controller: __dirname + "./sitemap.xml" would result in something like /path/to/project/src/controller/./sitemap.xml

And why should "../../sitemap.xml" work. If you only have "../../sitemap.xml" it is relative to the working directory which is the one where (i guess) index.js is located. So "../../sitemap.xml" will be resolved based on /path/to/project, so /path/to/project/../../sitemap.xml.

Due to that is either res.sendFile("./sitemap.xml") (relative to index.js) or res.sendFile(path.join(__dirname, "../../sitemap.xml")) (relative to the controller).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!