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?
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.
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.
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.
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.
You can use path.relative
:
var relativePath = path.relative(process.cwd(), someFilePath);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With