569 node内置模块path


path常见的API


在webpack中的使用

在webpack中获取路径或者起别名的地方也可以使用


01_路径的演练.js

const path = require('path');

const basePath = '/User/why';
const filename = 'abc.txt';

// const path = basePath + "/" + filename;

const filepath = path.resolve(basePath, filename);
console.log(filepath);


02_path其他方法.js

const path = require('path');

// 1.获取路径的信息
// const filepath = '/User/why/abc.txt';
// console.log(path.dirname(filepath)); // /User/why
// console.log(path.basename(filepath)); // abc.txt
// console.log(path.extname(filepath)); // .txt


// 2.join路径拼接
const basepath = '../User/why';
const filename = './abc.txt';
const othername = './why.js';

const filepath1 = path.join(basepath, filename);
// console.log(filepath1); // ..Userwhyabc.txt

// 3.resolve路径拼接
// resolve会判断拼接的路径字符串中,是否有以/或./或../开头的路径
// const filepath2 = path.resolve(basepath, filename, othername);
// console.log(filepath2); // F:前端why
odekejianday01_24Userwhyabc.txtwhy.js

const basepath2 = '/User/coderwhy';
// const filename2 = '/why/abc.txt'; // /why/abc.txt
// const filename2 = './why/abc.txt'; // /User/coderwhy/why/abc.txt
// const filename2 = 'why/abc.txt'; // /User/coderwhy/why/abc.txt

const filename2 = '../why/abc.txt'; // /User/coderwhy/why/abc.txt

const result = path.resolve(basepath2, filename2);
console.log(result);


03.使用esmodule加载.mjs

import path from 'path';

const basepath = '../User/why';
const filename = '/abc.txt';
const othername = '/why.js';

const filepath1 = path.join(basepath, filename);
console.log(filepath1);


原文地址:https://www.cnblogs.com/jianjie/p/14232273.html