Home > Software design >  Why path.resolve with string args print absolute path, but with variable args print relative path?
Why path.resolve with string args print absolute path, but with variable args print relative path?

Time:01-02

const path = require('path')

const file = path.join('/content', 'subfolder', 'first.txt')

const absoluteWithStrings = path.resolve(__dirname, 'content', 'subfolder', 'first.txt')
const absoluteWithVars = path.resolve(__dirname, file)

console.log(file)
console.log(absoluteWithStrings)
console.log(absoluteWithVars)

Why does absoluteWithStrings print the absolute path, BUT absoluteWithVars prints the relative path?

Screenshot shows outputenter image description here

CodePudding user response:

Both of these are absolute paths (they begin with /). The resolution algorithm goes right-to-left, not left-to-right, prepending each preceding path segment. In the second variable you're beginning the first string path segment with a slash, telling resolve that you want to start at /, effectively overriding the preceding __dirname.

  • Related