user2727195 user2727195 - 8 months ago 53
Node.js Question

path.join for the tmpDir returns two extra tokens (empty strings)


var tmp = path.join(os.tmpDir(), dir);
var segments = tmp.split(path.sep); // create directories/subdirectories
for(var i=0; i<segments.length; i++) {
var segment = segments.slice(0, i).join(path.sep);
console.log(i, segment.length, segment, fs.existsSync(segment));


0 0 '' false
1 0 '' false
2 4 '/var' true
3 12 '/var/folders' true


Why index 0 and 1 are empty strings?


Because of segments.slice(0, i)

The first iteration, it excludes the first element:

"slice extracts up to but not including end"

The second iteration, it includes the first element, which is empty because of how the path was split: tmp.split(path.sep), and since the path starts with a leading slash.

If you know it's always an absolute path, then start the loop at i=2. If a relative path might be inputted, you'll just have to start at i=1, and deal with the blank element at index 0 when working with absolute paths.