node.jsfs-extra

How to read json from different path in Nodejs?


When I had a very simple file structure without routers and controllers in my node express project, I can easily read and return properly the contents of a json file, using fs-extra.

But when I added some folders to folders (and learned routers+controllers), I'm now having a hard time.

If I do this, by having a require variable (I utilize VSCode's autocompletion to make sure my file path is correct):

const fs = require("fs-extra")
const json = require("../../jsons/emojis.json")

exports.getEmojis = async (req, res) => {
  try {
    const emojis = await fs.readJson(json)
    const pretty = JSON.stringify(emojis, null, 4)
    res.setHeader("Content-Type", "application/json")
    res.send(pretty)
  } catch (err) {
    console.log("Error fs readJSON: " + err.message)
    res.status(500).send({
      message: "Error getting emojis."
    })
  }
}

I get an error:

Error fs readJSON: The "path" argument must be of type string or an instance of Buffer or URL. Received an instance of Object


While if I put the string path directly to readJson like so:

const emojis = await fs.readJson("../../jsons/emojis.json")

I get an error:

Error fs readJSON: ENOENT: no such file or directory, open './emojis.json'


Edit: the file path is absolutely correct, like I mentioned I use VSCode.

emojis.json json file is under "jsons" folder, and that folder is 2 folders away from the controller file.

enter image description here


Solution

  • This should solve it:

    const path = require("path");
    const fullPath = path.resolve("../../jsons/emojis.json");
    const emojis = await fs.readJson(fullPath);