node相关模块文档
var path = require('path');
/**
* ./ 指向当前的工作路径
* __dirname 指向被执行 js 文件的绝对路径
*/
/**
* 获取url的最后一级
* @param {*} url
* @param {*} suffix 需要忽略的后缀
* @returns
*/
const lastPath = (url,suffix) => {
if (suffix) {
return path.basename(url,suffix);
} else {
return path.basename(url);
}
// eg:
// path.basename('/foo/bar/baz/asdf/quux.html');返回: 'quux.html'
// path.basename('/foo/bar/baz/asdf/quux.html', '.html');返回: 'quux'
}
module.exports.lastPath = lastPath;
// 获取路径
const getPath = (url) => {
return path.dirname(url);
// eg:
// path.dirname('/foo/bar/baz/asdf/quux'); 返回: '/foo/bar/baz/asdf'
}
module.exports.getPath = getPath;
// 获取文件后缀
const getSuffix = (url) => {
return path.extname(url);
// eg:
// path.dirname('/foo/bar/baz/asdf/quux.html'); 返回: '.html'
// path.dirname('/foo/bar/baz/asdf/quux'); 返回: ''
}
module.exports.getSuffix = getSuffix;
// 判断是否为绝对路径
const isAbsolute = (url) => {
return path.isAbsolute(url);
// eg:
// path.isAbsolute('/baz/..'); // true
// path.isAbsolute('qux/'); // false
}
module.exports.isAbsolute = isAbsolute;
// 组装绝对路径
const join = (...url) => {
return path.join(...url);
// path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// 返回:
// '/foo/bar/baz/asdf'
}
module.exports.join = join;
// 分解路径
const parse = (url) => {
return path.parse(url);
// path.parse('/home/user/dir/file.txt');
// 返回:
// { root: '/',
// dir: '/home/user/dir',
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
}
module.exports.parse = parse;