rajesh kumar
rajesh kumar

Reputation: 31

Node js fs.exists only searching file in current directory

I have setup process.env.path variables and fs.exists(fileName). Node is not able to find the file if it is not in its currently directory. Is there someway i can configure node to search for file in all directory mentioned in 'process.env.path'.

Upvotes: 0

Views: 107

Answers (1)

Maurits Rijk
Maurits Rijk

Reputation: 9985

This isn't supported out of the box. You will have to find a suitable npm package that already does this for you or write your own code. Something along the lines of the code that is in node-whereis:

var fs = require('fs');

function whereIsMyFile(filename){
    var pathSep = process.platform === 'win32' ? ';' : ':';

    var directories = process.env.PATH.split(pathSep);
    for (var i = 0; i < directories.length; i++) {
        var path = directories[i] + '/' + filename;
        if (fs.existsSync(path)) {
            return path;
        }
    }
    return null;
}

Upvotes: 1

Related Questions