Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS accessing file with relative path [duplicate]

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.

like image 570
lonelymo Avatar asked Sep 21 '15 22:09

lonelymo


People also ask

How do you pass a relative path in node JS?

relative() Method. The path. relative() method is used to find the relative path from a given path to another path based on the current working directory. If both the given paths are the same, it would resolve to a zero-length string.

What is __ Dirname NodeJS?

It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.

How do I copy files from one directory to another in node JS?

copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.


2 Answers

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.

like image 126
AerandiR Avatar answered Oct 01 '22 04:10

AerandiR


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

like image 32
AdityaParab Avatar answered Oct 01 '22 04:10

AdityaParab