简体   繁体   中英

Node.js fs ENOENT error

I am currently working on an ExpressJS app that reads a yaml file to json, and then sends the json to the front end to be used by Angular.

Here is the file structure for the project

server/
├── data/
│   └── file.yml
├── index.js
└── routes/
    └── index.js

In ./routes/ I have my index.js file which, surprise surprise, contains my routes. And here is the route that I am using to access the yml file:

app.get('/api/assets', (req,res) => {

    try {
      let doc = yaml.safeLoad(fs.readFileSync('../data/file.yml', 'utf8'));
      // console.log(doc);
      res.json(doc);
    } catch (err) {
      let doc = {
        "name": err.name,
        "reason": err.reason,
        "message": err.message
      }
      res.json(doc);
    }

  });

For whatever reason, after spinning up the server and hitting the /api/assets route, I get the following error:

{
  "name": "Error",
  "message": "ENOENT: no such file or directory, open 'tenant-assets.yml'"
}

I have tried a few things to get it working, such as changing the file name to ./data/file.yml and data/file.yml , thinking that it was calling them from the entry index.js. So, I am sort of stuck and don't know what is going on.

To use a relative path from the current file, the recommend way is to use path.join() and __dirname .

In your case:

const path = require('path');

app.get('/api/assets', (req, res) => {
    try {
        let doc = yaml.safeLoad(fs.readFileSync(path.join(__dirname, '../data/file.yml'), 'utf8'));
        // console.log(doc);
        res.json(doc);
    } catch (err) {
        let doc = {
            "name": err.name,
            "reason": err.reason,
            "message": err.message
        }
        res.json(doc);
    }
});

I realized that I was spinning up the server from what is effectively the root directory of the app. In order to fix it, I had to change the path to the file to ./server/data/file.yml .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM