Reputation: 28046
My Directory structure is something as below:
app/
server/
api/
user/
controller.js
images/
image1.jpeg
The problem is when reading image1.jpeg within controller.js I have to use a string like
var imagePath = __dirname + '/../../../images/images1.jpeg';
fs.readFile(imagePath, ()....
now the above works FINE. however what I don't like is this string '/../../../'
is there a better way to access files in the images/ folder ?
Upvotes: 0
Views: 735
Reputation: 19228
I use an npm module called node-app-root-path
to help me manage my paths within the NodeJS application.
See: https://github.com/inxilpro/node-app-root-path
To obtain the application's root path you would do require('app-root-path')
;
Example:
global.appRoot = require('app-root-path');
var imagePath = global.appRoot.resolve('server/images');
var img1 = imagePath + '/image1.jpeg';
fs.readFile(img1, ()....
Not sure whether is it a good idea or not but for this case I have stored the appRoot as a global variable and this is so that it will be available anywhere within my NodeJS application stack, even to some of my other NodeJs libraries.
There are many other usages noted in their documentation, have a look and see if it helps you too.
Upvotes: 0
Reputation: 106698
Short of passing the path to app/images
to the controller, that's about as good as you can do.
You could traverse the module.parent
references until module.parent
isn't set, if you can safely make assumptions about where your main script is. For example, if your main script is app.js
inside app/
, you could do something like:
var path = require('path');
var topLevel = module;
while (topLevel.parent)
topLevel = topLevel.parent;
topLevel = path.dirname(topLevel.filename);
var imagesBasePath = path.join(topLevel, 'images');
// ...
fs.readFile(path.join(imagesBasePath, 'images1.jpeg'), ...);
Upvotes: 1
Reputation: 3940
You could use path.relative
. You'd probably want to save these as constants but you could do the following to make things more readable.
Pass in the path to your current directory as the first parameter and the path to the image itself from the same parent directory (in this case app) and it will return the relative path from the current directory to the image.
// returns '/../../../images/images1.jpeg'
var relativePathToImage = path.relative(
'/app/server/api/user',
'/app/images/images1.jpeg');
var pathToImage = __dirname + relativePathToImage;
Upvotes: 1