runtimeZero runtimeZero - 1 year ago 87
Javascript Question

Obtaining path in nodejs

My Directory structure is something as below:



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 Source

I use an npm module called node-app-root-path to help me manage my paths within the NodeJS application.


To obtain the application's root path you would do require('app-root-path');


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download