Get parent directory name in Node.js

I am using Node.js, and I want to obtain the parent directory name for a file. I have the file "../test1/folder1/FolderIWant/test.txt".

I want to get "FolderIWant".

I have tried:

var path = require('path');
var parentDir = path.dirname(filename);

But it returns ../test1/folder1/FolderIWant.


Solution 1:

What you want is path.basename:

path.basename(path.dirname(filename))

Solution 2:

Better use @danielwolf's answer instead


Use split() and pop():

path.dirname(filename).split(path.sep).pop()

Solution 3:

Daniel Wolf's answer is correct, also if you want the full path of the parent dir:

require('path').resolve(__dirname, '..')

Solution 4:

const path = require("path")
path.dirname(path.basename(__dirname))

Solution 5:

process.mainModule property is deprecated in v14.0.0. If foo.js is run by node foo.js (e.g. somedir/foo.js"),

const path = require("path");

module.exports = path.dirname(require.main.filename);

result: somedir

Use require.main instead