Mykybo
Mykybo

Reputation: 1499

Using fs.readdir returns ENOENT on vps, but not on localhost

So I am working on a node js project and I want to load all files from one directory. Everything works on localhost, but when I push it to server, it throws this error:

Error: ENOENT, readdir './maps/'

The error is here (app.js):

        var dir='./maps/';
        fs.readdir(dir,function(err,files){
            if (err) throw err;
            files.forEach(function(file){
                fs.readFile(dir+file,'utf-8',function(err,data){
                    if (err) throw err;                        
                    //code..
                    }
                });
            });
        });

I triple checked the directory tree on server and it is indeed the same as on localhost, so I have no idea what's happening here.

The directory tree looks like this (both on server and localhost):

src
    app.js
    maps
        map1.json
        map2.json
    routes
        index.js
        and so on...

The server is running on amazon linux.

Upvotes: 0

Views: 392

Answers (1)

You usually run into this when you're starting your server from a different dir locally than remotely.

If you run node app.js from $\src\> locally, and Amazon actually runs node src\app.js, for instance, none of your relative dirs will resolve correctly. A simple way to check is to log what process.cwd() reports at the start of your app.js, so you know which directory it's actually getting executed in. You can then even -if you want- use process.chdir() to navigate the app.js script to make sure all your relative dirs work using something like

var path = require("path");
process.chdir(path.dirname(__filename));

which will use the location of "this script", which is the global __filename in Nodejs (this is an absolute file location btw), find its owning directory (via the path module), then changes the active directory to be the same as where the current file is located.

Upvotes: 1

Related Questions