path
参考文档:http://nodejs.cn/api/path.html
const {normalize} = require('path'); // ES6语法
// 相当于 const normalize = require('path').normalize;
// 标准化路径
console.log(normalize('/usr///local/bin'));
console.log(normalize('/usr/local/../bin'));
输入 node normalize.js
,可以修正路径
路径拼接:
const {join} = require('path');
console.log(join('/usr/', 'local', 'bin'))
将相对路径转化为绝对路径:
const {resolve} = require('path');
console.log(resolve('./'));
basename,dirname,extname
const {basename, dirname, extname} = require('path');
const filePath = '/usr/local/bin/no.txt';
console.log(basename(filePath));
console.log(dirname(filePath));
console.log(extname(filePath));
parse与format
const {parse, format} = require('path');
const filePath = '/usr/local/node_modules/n/iloveu.json';
const ret = parse(filePath);
console.log(ret);
const path = format(ret);
console.log(path);
与操作系统有关的一些 sep delimiter win32 posix
const {sep, delimiter, win32, posix} = require('path');
console.log('sep:', sep);
console.log('win sep:', win32.sep);
console.log('posix sep:', posix.sep);
console.log('PATH:', process.env.PATH);
console.log('delimiter:', delimiter);
console.log('win delimiter:', win32.delimiter);
console.log('posix delimiter:', posix.delimiter);
delimiter: // 分割符,windows下是;(分号)Linux是:(冒号)
const path = require('path');
console.log('__dirname:', __dirname);
console.log('process.cwd():', process.cwd());
console.log('./ :', path.resolve('./'));
输入如下命令:node ./nodejs/path.js
path:
- __dirname,__filename总是返回文件的绝对路径
- process.cwd()总是返回执行node命令所在文件夹
相对路径./
- 在require方法中总是相对当前文件所在文件夹
- 在其他地方和process.cwd()一样,相对node启动文件夹