user1438940 user1438940 - 1 month ago 4x
Linux Question

Proper way to reference files relative to application root in Node.JS

I have a Node.JS application running on Linux at AWS EC2 that uses the fs module to read in HTML template files. Here is the current structure of the application:


The HTML templates will always be in that location, however, the template-reading-service may move around to different locations (deeper subdirectories, etc.) From within the template-reading-service I use fs.readFileSync() to load the file, like so:

var templateContent = fs.readFileSync('./templates/my-template.html', 'utf8');

This throws the following error:

Error: ENOENT, no such file or directory './templates/my-template.html'

I'm assuming that is because the path './' is resolving to the '/services/' directory and not the application root. I've also tried changing the path to '../templates/my-template.html' and that worked, but it seems brittle because I imagine that is just resolving relative to 'up one directory'. If I move the template-reading-service to a deeper subdirectory, that path will break.

So, what is the proper way to reference files relative to the root of the application?



var templateContent = fs.readFileSync(path.join(__dirname, '../templates') + '/my-template.html', 'utf8');