在 Node.js 中获取父目录名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42956127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get parent directory name in Node.js
提问by Me5
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".
我正在使用 Node.js,我想获取文件的父目录名称。我有文件"../test1/folder1/FolderIWant/test.txt"。
I want to get "FolderIWant".
我想得到"FolderIWant"。
I have tried:
我试过了:
var path = require('path');
var parentDir = path.dirname(filename);
But it returns ../test1/folder1/FolderIWant.
但它返回../test1/folder1/FolderIWant。
采纳答案by baao
Better use @danielwolf's answer instead
Use split()and pop():
使用split()和pop():
path.dirname(filename).split(path.sep).pop()
回答by Daniel Wolf
回答by Dirigible
Daniel Wolf's answer is correct, also if you want the full path of the parent dir:
丹尼尔沃尔夫的回答是正确的,如果你想要父目录的完整路径:
require('path').resolve(__dirname, '..')
回答by C Williams
const path = require('path');
module.exports = path.dirname(process.mainModule.filename)
Use this anywhere to get the root directory
在任何地方使用它来获取根目录
回答by DevOpsIsTheNameOfTheGame
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:
从 06-2019 开始使用 node,我遇到了一个问题,只能访问filename. 所以相反,我只是稍微修改了一下并使用了:
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.
所以现在你得到了你所在的当前目录的目录名,而不是完整路径。尽管以前的答案似乎对其他人有用,但对我而言,它引起了问题,因为节点正在寻找常量或变量但找不到。

