部分内置模块
一.url
url模块,专门用来处理url相关操作
1. parse(urlString,[parseQueryString]) 中括号中的参数,可传可不传
/**
* 对一个url字符串做解析,返回一个url对象
* url.parse(urlString,[parseQueryString])
*
* parseQueryString 接受一个布尔值,当为true时,会自动将解析出来的query部分转成对
* 象
* 默认是false query的格式是username=zhangsan&age=18
* 设置为true query的格式是{ username: 'zhangsan', age: '18' }
**/
//引入内置模块url
var url = require('url');
//url地址
const urlstr = "http://localhost:3000?username=zhangsan&age=18#hash";
//解析后的url对象
const parseStr = url.parse(urlstr, true);
console.log(parseStr);
返回结果
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:3000',
port: '3000',
hostname: 'localhost',
hash: '#hash',
search: '?username=zhangsan&age=18',
query: [Object: null prototype] { username: 'zhangsan', age: '18' },
pathname: '/',
path: '/?username=zhangsan&age=18',
href: 'http://localhost:3000/?username=zhangsan&age=18#hash'
}
红色url地址上方的是 url 模块所规定的 url的组成部分。(过时的)
红色url地址下方的是 WHATWG URL Standard 规范所规定的 url的组成部分
2.url.format()
/**
* 将一个url对象,转换成url字符串
* url.format(urlObj)
*/
var urlObj={
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:3000',
port: '3000',
hostname: 'localhost',
hash: '#hash',
search: '?username=zhangsan&age=18',
query: 'username=zhangsan&age=18',
pathname: '/',
path: '/?username=zhangsan&age=18',
href: 'http://localhost:3000/?username=zhangsan&age=18#hash'
}
console.log(url.format(urlObj)) ;
//返回结果 http://localhost:3000/?username=zhangsan&age=18#hash
上述url模块是过时的,WHATWG 组织规定了一套新的url规范
在javascript中,提供了一个URL构造函数,可以直接去使用,不需要引入
3.new URL(urlStr) 实例化一个url对象,返回的是新标准的url组成对象
const urlstr = "http://localhost:3000?username=zhangsan&age=18#hash";
var urlObj = new URL(urlstr);
//使用get()方法获取其中某个参数
console.log(urlObj.searchParams.get('username'));//zhangsan
console.log(urlObj.searchParams.get('age'));//18
//url对象转为url字符串
console.log(urlObj.toString());
//返回结果 http://localhost:3000/?username=zhangsan&age=18#hash
二. querystring
querystring 模块,专门用来处理形如key1=value&key2=value2这种格式的数据
1.querystring.parse(str, [sep], [eq], [options])
/**
* 对一个查询字符串,解析成查询对象
* querystring.parse(str, [sep], [eq], [options])
* str 欲转换的字符串
* sep 设置分隔符,默认为 ‘&'
* eq 设置赋值符,默认为 ‘='
* [options] maxKeys 可接受字符串的最大长度,默认为1000
*/
const querystring=require("querystring");
const urlstr1 = "key1=value1&key2=value2";
console.log(querystring.parse(urlstr1));//{ key1: 'value1', key2: 'value2' }
const urlstr2 = "key1=value1@key2=value2";
console.log(querystring.parse(urlstr2,'@'));//{ key1: 'value1', key2: 'value2' }
const urlstr3 = "key1-value1@key2-value2";
console.log(querystring.parse(urlstr3,'@','-'));//{ key1: 'value1', key2: 'value2' }
2.querystring.stringifyobj[, sep[, eq]] 将查询对象转换成查询字符串
/**
* 将查询对象转换成查询字符串
*
* querystring.stringify(obj[, sep[, eq]])
*
* sep 规定 键值对之间的分隔符是什么,默认是 &
*
* eq 规定 键值之间的分隔符是什么,默认是 =
*/
var obj={ key1: 'value1', key2: 'value2' };
console.log( querystring.stringify(obj));//key1=value1&key2=value2
console.log( querystring.stringify(obj,'@'));//key1=value1@key2=value2
console.log( querystring.stringify(obj,'@','-'));//key1-value1@key2-value2
三.fs
fs模块,专门用来处理文件相关的操作,读文件,写文件等
1.fs.readFile(file[, options], callback) 异步的读取文件
const fs=require('fs');
/**
* 异步的读取文件
*
* fs.readFile(file[, options], callback)
* path:要读取的文件
* options 读取文件时的选项,比如:文件编码utf8。选填。
* callback: 回调函数
* error: 错误对象, 如果他存在,则说明读取操作失败
* data: 读取到的文件内容
*/
fs.readFile('./url.js','utf-8',(error,data)=>{
//判断error是否存在
if(error){
console.log("读取文件失败",error.message);
return;
}
console.log("读取文件成功",data.toString());
});
读文件注意:
-
该操作采用异步执行
-
回调函数有两个参数,分别是err和data
-
如果读取文件时没有指定编码,返回的是二进制数据,如指定编码utf8,会返回指定的编码数据。
-
只要异步操作,回调函数第一个都是错误对象err优先
2.fs.readFileSync(path) 同步的读取文件,返回值是文件的内容
/**
* 同步的读取文件,返回值是文件的内容
*
* fs.readFileSync(path)
* path: 要读取的文件
*/
//同步读取文件,做错误处理,抛出错误,避免程序挂掉
try {
const fileData = fs.readFileSync('./url.js');
console.log(fileData.toString());
} catch (error) {
console.log(error.message);
}
3.fs.writeFile(path, data, callback)异步的写文件
/**
* 异步的写文件,
* 注意:
* 1. 文件不存在也能写入
* 2. 如果路径中包含有不存在的文件夹,那么会失败
*
* fs.writeFile(path, data, callback)
* - path: 要写的文件路径
* - data: 要写的内容
* - callback: 回调函数
* - error: 错误对象,如果有值,说明写失败/
* 否则就表示写入成功
*/
fs.writeFile('./write.txt', "hello world", (error) => {
if (error) {
console.log('写入失败', error.message);
return;
}
console.log('写入成功');
});
注意:
- 文件不存在也能写入
- 如果路径中包含有不存在的文件夹,那么会失败
4.fs.writeFileSync(path, data)同步的写文件
/**
* 同步的写文件
*
* fs.writeFileSync(path, data)
*
* - path:要写的文件路径
* - data:要写入的内容
*/
try {
fs.writeFileSync('./txt/write-1.txt', 'hello world');
console.log('写入成功');
} catch (error) {
console.log('写入失败', error.message);
}
四.path
path 模块,专门用来处理路径相关的操作
1.path.resolve([…path]) 处理多个 path ,结合成一个绝对路径并返回
const path = require("path");
/**
* 处理多个 path ,结合成一个绝对路径并返回
*
* path.resolve([...path])
* [...path] 可以传递多个路径参数
*/
var filepath = path.resolve('./day02-0324\day02', './path.js');
console.log(filepath);//E:\test\node\day02-0324\day02\day02-0324day02\path.js
2.path.join([…path])处理多个 path, 结合成一个路径并返回
/**
* 处理多个 path, 结合成一个路径并返回
*
* path.join([...path])
*/
var filepath = path.join('./day02-0324\day02', './path.js');
console.log(filepath);//day02-0324day02\path.js
问题来了,path.join()和path.resolve()有什么区别,这是面试经常问到的
1.返回值不同,path.resolve()总是返回一个绝对路径,而path.join()只是简单的将路径拼接
2.处理不同:path.resolve()如果有某个参数路径是绝对路径(E:/),这个参数路径前面的参数路径统一丢弃,而path.join(),直接全部拼接
上代码
// path.join和path.resolve区别
var filepath=path.resolve('./day02-0324\day02','E:/','D:/','./path.js');
console.log(filepath);//D:\path.js
var filepath=path.join('./day02-0324\day02','E:/','D:/','./path.js');
console.log(filepath);//day02-0324day02\E:\D:\path.js
再来一个问题,如果我想用path.join()也得到绝对路径怎么办?
var filepath = path.resolve('./day02-0324\day02', './path.js');
console.log(filepath);//E:\test\node\day02-0324\day02\day02-0324\day02\path.js
//只要拼接的前者使用绝对路径也可以得到
var filepath=path.join("E:\test\node\day02-0324\day02\day02-0324\day02",'path.js');
console.log(filepath);//E:\test\node\day02-0324\day02\day02-0324\day02\path.js
答案是:使用path.join想得到绝对路径时,拼接的前者使用绝对路径即可
另外,我们在实际开发过程中,肯定是不能使用绝对路径的,因为,如果我的项目文件移动位置了,那肯定就报错了,这时引入一个 __dirname 当前模块的目录名
var filepath=path.join(__dirname,'path.js');
console.log(filepath);//E:\test\node\day02-0324\day02\path.js