Jim Jones
Jim Jones

Reputation: 2709

How do I ensure a local directory with fs.readdir()

So I have an express server that upon a GET request, returns a json file.

app.get('/server-generated/pages.json',function(req, res) {
  fs.readdir('public/pages',function(err,data){
    res.json(data || err);//temp error checking
  });
});

it works just fine when I run node app or forever app in its directory but when I run it as a forever service from Ubuntu upstart on startup exec forever start /home/*****/transfer/app.js I get this in response

{
  "errno": 34,
  "code": "ENOENT",
  "path": "public/pages"
}

which is directory error if I'm right? the full folder hierarchy goes like this /home/****/transfer/public/pages

How would I write a directory that would work on any computer (windows/ubuntu) running the app locally or from upstart?

Upvotes: 1

Views: 3736

Answers (1)

micnic
micnic

Reputation: 11245

you should use the path relative to the directory where the module is:

var path = require('path');

fs.readdir(path.join(__dirname, 'public/pages'), function(err, data) {
    res.json(data || err);
});

Upvotes: 4

Related Questions