Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

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:

/server.js /templates/my-template.html /services/template-reading-service.js 

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?

like image 385
user1438940 Avatar asked Oct 24 '12 15:10

user1438940


People also ask

How do you create a relative path in NodeJS?

relative() Method. The path. relative() method is used to find the relative path from a given path to another path based on the current working directory. If both the given paths are the same, it would resolve to a zero-length string.

How do I write a file path in node JS?

js: var fs = require('fs') var newPath = "E:\\Thevan"; var oldPath = "E:\\Thevan\\Docs\\something. mp4"; exports. uploadFile = function (req, res) { fs. readFile(oldPath, function(err, data) { fs.

What is __ Dirname in node?

It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.


1 Answers

Try

var templateContent = fs.readFileSync(path.join(__dirname, '../templates') + '/my-template.html', 'utf8'); 
like image 108
jwchang Avatar answered Sep 22 '22 07:09

jwchang