可以使用什么自定义函数(在 Node 中),如果传递三个参数,即 filePath
、basePath
和 destPath
,它将返回一个新路径。例如。
函数签名示例
var path = require('path'); // Nodes `path` module is likely to help?
/**
* Returns a new filepath
* @param {String} filePath - The path to the source file.
* @param {String} basePath - The path to determine which part of the
* FilePath argument is to be appended to the destPath argument.
* @param {String} destPath - The destination file path.
* @return {String} The new filepath.
*/
function foo(filePath, basePath, destPath) {
// ... ?
return newFilePath;
}
用法示例:
下面是调用该函数的一些示例以及我期望在给定传递的参数的情况下返回的值:
// Example A
var a = foo('./foo/bar/baz/quux/filename.json', 'foo/bar/baz/', './dist');
console.log(a) // --> 'dist/baz/quux/filename.json'
// Example B
var b = foo('./a/b/c/d/e/filename.png', './a/b/c', './images/logos/');
console.log(b) // --> 'images/logos/c/d/e/filename.png'
// Example C
var c = foo('images/a/b/filename.png', './images/a/b', 'pictures/');
console.log(c) // --> 'pictures/b/filename.png'
更多信息
- 正如您从示例函数调用中看到的,
basePath
String
将通知函数应在何处 trimfilePath
值,其用途类似于 gulp base option与gulp.src()
函数一起使用。 - 参数
String
值(即路径)始终是相对的,但是,它们有时会包含当前目录前缀./
,有时则不包含。尾部正斜杠/
可能出现在路径String
上,也可能不出现。 - 该解决方案必须跨平台运行,没有任何额外的依赖项。它还必须可用于早期 Node 版本(>= 0.10.28)
- 我曾多次尝试使用 path 的实用程序,但均以失败告终。模块,例如
path.normalize
然后分割Array
等等。但是,我非常确定 path解决方案中将使用模块。
提前致谢。
最佳答案
您可以使用简单的字符串替换来实现此目的。只需规范化之前的路径即可。
- filePath 和 basePath:如果它们以
./
开头,请将其删除。 - basePath :如果它以
/
结尾,请将其删除,然后删除最后一个路径部分(第一个示例中的baz
) filePath.replace(basePath, destPath)
关于javascript - Node/JavaScript 函数返回一个新路径,给定文件路径、基本路径和新的目标路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863259/