[英]get the middle folder of a file from a path in node.js
I have a file under "modules/test/main/main.js" and i want to get the "test" folder : 我在“ modules / test / main / main.js”下有一个文件,我想获取“ test”文件夹:
I tried this code but all i get is the main
folder 我尝试了这段代码,但我得到的只是main
文件夹
path.basename(path.dirname('modules/test/main/main.js'))
You can split on /
and than drop off last item as it is file name. 您可以分割/
然后删除最后一项,因为它是文件名。 and than take the middle element 然后拿中间的元素
let path = `modules/test/main/main.js` let middle = path.split(/\\//g) middle.pop() console.log(middle[Math.floor(middle.length-1)/2])
You can use path.join()
to go up two directories, and then get the basename
of the directory: 您可以使用path.join()
进入两个目录,然后获取目录的basename
:
const p = 'modules/test/main/main.js';
const dir = path.basename(path.join(p, '../..')); // 'test'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.