NodeJS accessing file with relative path

node.jsExpressFs

node.js Problem Overview


It seemed like a straight forward problem. But I amn't able to crack this. Within helper1.js I would like to access foobar.json (from config/dev/)

root
  -config
   --dev
    ---foobar.json
  -helpers
   --helper1.js

I couldn't get this to work https://stackoverflow.com/questions/7083045/fs-how-do-i-locate-a-parent-folder

Any help here would be great.

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlonelymoView Question on Stackoverflow
Solution 1 - node.jsAerandiRView Answer on Stackoverflow
Solution 2 - node.jsAdityaParabView Answer on Stackoverflow