从nodejs中的路径中剥离父目录的常见方法是什么

What is the common way to strip out the parent directory from the path in nodejs?

本文关键字:常见 方法 是什么 剥离 nodejs 路径      更新时间:2023-09-26

假设路径是/foo/bar/baz.json,我想要/bar/baza.json。使用nodejs路径的一般方法是什么?

Node.js中有一个内置函数:

require('path').relative('/foo', '/foo/bar/baz.json');
// 'bar/baz.json'

关于:

var path = require('path');
var myPath = "/foo/bar/baz.json";
var pathItems = myPath.split(path.sep);
pathItems = pathItems.splice(2);
var result = path.sep + pathItems.join(path.sep);
console.log(result);
// "/bar/baz.json"

您可以使用path.isAbsolute()来决定如何处理第一个"/"