Home > Net >  How to res.sendFile() a file that is in a different directory for Express.js webapp?
How to res.sendFile() a file that is in a different directory for Express.js webapp?

Time:03-05

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

CodePudding user response:

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).

  • Related