Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js get relative to project/src path of file

In my node.js project I use log4js and I want my logs to have name of the file where log record was added. So I use __filename but it gives me absolute path

var logger = log4js.getLogger(__filename) 

So it gives me logs like this:

[1999-01-01 00:00:00] [DEBUG] /Users/whatever/myproject/src/services/users something happened 

But I want the path to be relative to my project/src folder. Like this:

[1999-01-01 00:00:00] [DEBUG] services/users something happened 

What is the best way to achieve this?

like image 404
Vladislav Lezhnin Avatar asked Jan 09 '16 17:01

Vladislav Lezhnin


People also ask

How do I find the relative path in node JS?

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 get the project root path in node JS?

At runtime node creates a registry of the full paths of all loaded files. The modules are loaded first, and thus at the top of this registry. By selecting the first element of the registry and returning the path before the 'node_modules' directory we are able to determine the root of the application.

How do I pass 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.

How do you specify relative paths?

Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy. A single dot represents the current directory itself.


1 Answers

You can use path.relative:

var relativePath = path.relative(process.cwd(), someFilePath); 
like image 86
Denys Séguret Avatar answered Sep 20 '22 10:09

Denys Séguret