在 Node.js 中获取父目录名

我正在使用 Node.js,我希望获得 我有文件 "../test1/folder1/FolderIWant/test.txt"

我想得到 "FolderIWant"

我试过了:

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

但它返回 ../test1/folder1/FolderIWant

131898 次浏览

最好用@DanielWolf 的答案


使用 split()pop():

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

你想要的是 path.basename:

path.basename(path.dirname(filename))

丹尼尔沃尔夫的回答是正确的,如果你想要父母目录的完整路径:

require('path').resolve(__dirname, '..')
const path = require('path');


module.exports = path.dirname(process.mainModule.filename)

在任何地方都可以使用它来获取根目录

使用截至06-2019年的 node,我遇到了仅访问 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.

如果 foo.js 由 node foo.js运行(例如 somdir/foo.js) ,

const path = require("path");


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

result: somedir

使用 reque.main 代替

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

最简单的方式没有任何节点模块如路径。您可以通过以下方式轻松获得根文件夹名称。

var rootFolder = __dirname.split('/').pop();
console.log(rootFolder);

虽然在这里的答案有些工作,我发现使用流行的 App-root-path模块一个更好的锚点,从中指定一个路径。

import { path as arp } from 'app-root-path'
import path from 'path'


const root = path.resolve(arp, '../') // the parent of the root path


export const rootDirname = root

例子用法如下:

import { rootDirname } from './functions/src/utils/root-dirname'
import { getJsonFromFile } from './app/utils/get-json-from-file'


const firebaseJson = getJsonFromFile(`${rootDirname}/firebase.json`)

也许不是这里的最佳答案,但是一个没有被其他答案覆盖的选项。

典型的 __dirname解决方案不适用于 ESM 范围。为了在目录树中向上移动一级,我想出了以下解决方案:

import { fileURLToPath } from "url";
import path from "path";


const __filename = fileURLToPath(import.meta.url);
// First find out the __dirname, then resolve to one higher level in the dir tree
const __dirname = path.resolve(path.dirname(__filename), "../");

If you only need the absolute directory path the file resides in, you can leave out the path.resolve() call.