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
What you want is path.basename:
path.basename(path.dirname(filename))
Daniel Wolf's answer is correct, also if you want the full path of the parent dir:
require('path').resolve(__dirname, '..')
Simplest way without any node modules like the path. You can easily do in the following manner to get the root folder name.
var rootFolder = __dirname.split('/').pop();
console.log(rootFolder);
const path = require('path');
module.exports = path.dirname(process.mainModule.filename)
Use this anywhere to get the root directory
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
Using node as of 06-2019, I ran into an issue for accessing just filename
.
So instead, I just modified it a tiny bit and used:
path.dirname(__filename).split(path.sep).pop()
so now you get the directory name of the current directory you are in and not the full path. Although the previous answers seem to possibly work for others, for me it caused issues as node was looking for a const or a variable but couldn't find one.