Get Absolute Path of File from Relative Path in Node.js
Relative paths are convenient in that they specify the path of a file relative to the current working directory. However, they can also cause some issues due to ambiguity, and having the absolute path of a file is needed to be more explicit and avoid errors.
Here we'll see how to turn a relative path into an absolute path for a file in Node.js
The built-in path
module provides a method called resolve
that takes a relative path and a base path and returns the absolute path of the file.
const path = require('path');
let relativePath = './app.js';
let absolutePath = path.resolve(relativePath);
console.log(absolutePath);
// Prints: /Users/scott/projects/skynet/app.js
Here the resolve
method knows that it's working with a relative path since it begins with ./
and that it should be resolved relative to the current working directory.
If you start your path with /
, it will be treated as an absolute path. Sending an absolute path to resolve
will just have it return the same path as there is nothing to resolve.
You can also remove the ./
from the beginning of the path and the resolve
method will still know that it's working with a relative path.
const path = require('path');
let relativePath = 't1000.js';
let absolutePath = path.resolve(relativePath);
console.log(absolutePath);
// Prints: /Users/scott/projects/skynet/t1000.js
One other feature that resolve
does have is that it can take multiple paths as arguments and resolve them into a single absolute path.
const path = require('path');
let relativePath = 'driver.c';
let absolutePath = path.resolve('./neural-net-cpu', relativePath);
console.log(absolutePath);
// Prints: /Users/scott/projects/skynet/neural-net-cpu/driver.c
The method can take any number of arguments, all of which will be joined together in a single path. Note that if any of the provided arguments given are absolute paths, all paths given before it will be ignored.