NodeJS基础API-path相关的问题basename,extname,dirname,parse,format,sep,delimiter,win32,posix

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 ,可以修正路径

/usr/local/bin
/usr/bin

路径拼接:

const {join} = require('path');
console.log(join('/usr/', 'local', 'bin'))

/usr/local/bin

将相对路径转化为绝对路径:

const {resolve} = require('path');
console.log(resolve('./'));

/home/dex/web/nodejs

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));

no.txt
/usr/local/bin
.txt

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);

{ root: '/',
dir: '/usr/local/node_modules/n',
base: 'iloveu.json',
ext: '.json',
name: 'iloveu' }
/usr/local/node_modules/n/iloveu.json

与操作系统有关的一些 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);

sep: /
win sep:
posix sep: /
PATH: /home/dex/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
delimiter: :
win 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

__dirname: /home/dex/web/nodejs
process.cwd(): /home/dex/web
./ : /home/dex/web

path:

  • __dirname,__filename总是返回文件的绝对路径
  • process.cwd()总是返回执行node命令所在文件夹

相对路径./

  • 在require方法中总是相对当前文件所在文件夹
  • 在其他地方和process.cwd()一样,相对node启动文件夹
posted @ 2018-12-07 16:31  cicarius  阅读(390)  评论(0编辑  收藏  举报