NodeJS accessing file with relative path [duplicate] NodeJS accessing file with relative path [duplicate] express express

NodeJS accessing file with relative path [duplicate]


You can use the path module to join the path of the directory in which helper1.js lives to the relative path of foobar.json. This will give you the absolute path to foobar.json.

var fs = require('fs');var path = require('path');var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');var jsonString = fs.readFileSync(jsonPath, 'utf8');

This should work on Linux, OSX, and Windows assuming a UTF8 encoding.


Simple! The folder named .. is the parent folder, so you can make the path to the file you need as such

var foobar = require('../config/dev/foobar.json');

If you needed to go up two levels, you would write ../../ etc

Some more details about this in this SO answer and it's comments