runtimeZero runtimeZero - 3 months ago 12
Javascript Question

Obtaining path in nodejs

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 ?

Answer

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.

Comments