sushmit sarmah
sushmit sarmah

Reputation: 7728

Node.js accessing files from inside modules

I am trying to access a file from inside a module. I have given the file location inside module as below.My module folder is called helper.

__dirname + "/../public/lib/objects"

500 Error: ENOENT, no such file or directory '/home/sushmitsarmah/projects/app/helpers/public/lib/objects'

It gives me an error with location being helper/public/lib/objects. I tried this next:

__dirname + "/../../public/lib/objects". This also gives me an error.

How should I access the public folder? In the directory structure helper and public are in the same level.

folder structure:

app
 --helpers
     --getData.js
 --public
     --lib
       --objects
 --views
 --app.js

In app.js I call: var getdata = require('./helpers/getdata').getData;

From inside getData.js I want to access the objects folder.

Thanks

Upvotes: 0

Views: 1868

Answers (1)

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

Note that __dirname points the directory that the currently executing script resides in. So in our case it is the directory where script is located. So the current working directory will always point to the folder of app.js where as the __dirname will change according to the file which is in execution.

So your path should be

__dirname + "/public/lib/objects" //from app.js

note:

In the folder structure updated above, when you are in getData.js, the value of __dirname will be "/rootpath/app/helpers". To get to objects folder from there, you have to do

__dirname + "/../public/lib/objects" //from getData.js

Upvotes: 2

Related Questions