12. 常用知识点
于2022-11-07 14:29:35发布
35
path.parse(路径解析)
const path = require('path');
const url1 = "C://file/images/1.jpg";
const url2 = "http://www.baidu.com/images/1.jpg";
console.log(path.parse(url1));
console.log(path.parse(url2));
输出
{
root: 'C:/',
dir: 'C://file/images',
base: '1.jpg',
ext: '.jpg',
name: '1'
}
{
root: '',
dir: 'http://www.baidu.com/images',
base: '1.jpg',
ext: '.jpg',
name: '1'
}
url解析(url.parse)
const url = require('url');
let str = 'http://www.baidu.com?search=xxx';
console.log( url.parse(str) );
console.log( url.parse(str).pathname );
输出
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?search=xxx',
query: 'search=xxx', //这里是key=value的形式
pathname: '/',
path: '/?search=xxx',
href: 'http://www.baidu.com/?search=xxx'
}
/
url.parse后面还可以传入一个布尔值,代表是否把query的key=value改成json对象。如 :
const url = require('url');
let str = 'http://www.baidu.com?search=xxx';
console.log( url.parse(str,true) );
输入 :
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?search=xxx',
query: [Object: null prototype] { search: 'xxx' }, //这里和上面不同
pathname: '/',
path: '/?search=xxx',
href: 'http://www.baidu.com/?search=xxx'
}
url.parse(str).pathname 和 req.url的区别
const url = require('url');
const http = require('http');
http.createServer((req,res)=>{
if (req.url === '/favicon.ico') { return; }
console.log('req.url = ' + req.url);
console.log('url.parse = ' + url.parse(req.url).pathname);
res.end();
}).listen(8080);
在浏览器上输入 :
http://localhost:8080/?name=tom&age=18
输出 :
req.url = /?name=tom&age=18
url.parse = /
req.url会携带上?后面的参数,而url.parse不会
获取文件的后缀名(path.extname)
const path = require('path');
let str = 'index.html';
console.log( path.extname(str) );
输出 :
.html
qs.parse (把字符串user=tom&password=12345解析成一个json对象)
const qs = require('querystring');
let str = 'user=tom&password=12345';
let obj = qs.parse(str);
console.log(`user=${obj.user}-------password=${obj.password}`);
输出 :
user=tom-------password=12345
重命名文件(rename)
const fs = require('fs');
fs.rename('./a.txt', './b.txt', (err) => { // 异步
console.log(err);
});
fs.renameSync('./a.txt', './b.txt'); // 同步