119

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 fs: how do I locate a parent folder?

Any help here would be great.

Community
  • 1
  • 1
lonelymo
  • 3,972
  • 6
  • 28
  • 36
  • 1
    `..\config\dev\foobar.json` – Ben Sep 21 '15 at 22:53
  • 2
    It would be better if you can just save your json data in `.js` file (instead of `.json`) And then from the `.js` file `module.exports` it. :) – AdityaParab Sep 22 '15 at 03:55
  • 4
    @AdityaParab: If you save you JSON file as .json instead of .js then you don't need to module.export it - you can require it directly. JSON file are automatically completely exported (or to put it another way, JSON files are supported by `require()`) – slebetman Sep 22 '15 at 04:13
  • @slebetman js files are more flexible, JSON requires double quotes, doesn't allow comments, etc.. One could use JSON5 or other similar format, but then you need a lib to read it. Js also allows dynamic data generation, from a function for example – Bernardo Dal Corno Jan 30 '20 at 14:34
  • 1
    The real reason to use .js over .json text files is really easy to explain: comments... ;) – jrypkahauer Apr 20 '20 at 00:24

2 Answers2

273

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.

AerandiR
  • 5,260
  • 2
  • 20
  • 22
19

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

Dheeraj Bhaskar
  • 18,633
  • 9
  • 63
  • 66
AdityaParab
  • 7,024
  • 3
  • 27
  • 40
  • 2
    Please add some explanation to your code here. – Shamas S Sep 22 '15 at 07:04
  • 13
    This will only work on json/js file. It will not work on other types of files like xml. Better approach is path.join() – gramcha Aug 24 '17 at 09:05
  • 5
    This is not a very good solution if you are calling the file from another folder. If you structure is src->utils->someUtilFile.js and also have a second file src->logic->someLogic.js and you use ../../utils/someUtilFile.js this will work. but if you are calling someUtilFile.js from a different structure directory this will not work. – Isan Rivkin Dec 07 '17 at 11:40