nodejs常用模块
path模块
path
模块提供用于处理文件路径和目录路径的实用工具
日常用到的最多的方法为join()
方法
//path.join() 方法使用平台特定(即不同系统输出结果不同)的分隔符作为定界符将所有给定的 path 片段连接在一起,然后规范化生成的路径
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// 返回: '/foo/bar/baz/asdf'
//常常用到的实例,设置静态资源管理
app.use(express.static(path.join(__dirname, 'public')));
url模块
url
模块常用方法有parse()
、format()
两个方法
url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash");
/*
返回值:
{
protocol: 'http:',
slashes: true,
auth: 'user:pass',
host: 'host.com:8080',
port: '8080',
hostname: 'host.com',
hash: '#hash',
search: '?query=string',
query: 'query=string',
pathname: '/p/a/t/h',
path: '/p/a/t/h?query=string',
href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
}
没有设置第二个参数为true时,query属性为一个字符串类型,否则返回 query: { query: 'string' }
*/
url.format({
protocol: 'http:',
slashes: true,
auth: 'user:pass',
host: 'host.com:8080',
port: '8080',
hostname: 'host.com',
hash: '#hash',
search: '?query=string',
query: 'query=string',
pathname: '/p/a/t/h',
path: '/p/a/t/h?query=string',
href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
});
/*
返回值:
'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
*/
queryString模块
queryString
常用方法有两个 querystring.parse
和querystring.stringify
//通常在通过http传输前后使用qs讲对象或字符串进行转换
const querystring = require("querystring");
var obj = {name:"张三",age:31};
// 对象转字符串
var res = querystring.stringify(obj);
console.log(res); //name=%E5%BC%A0%E4%B8%89&age=31
// 字符串转对象
var newobj = querystring.parse(res);
console.log(newobj); //{ name: '张三', age: '31'}
cheerio模块
cheerio
模块是一个类似jquery的模块,能够将一个网页解析为DOM ,常用于爬虫解析。
//爬虫实例
const http = require('https'),
cheerio = require('cheerio'),
log = console.log,
print = require('util').debuglog('crawler'),
addr = 'https://segmentfault.com/lives/free';
http.get(addr, (res) => {
var result = '';
res.on('data', (data) => {
result += data.toString('utf8');
});
res.on('end', () => {
print(result);
var $ = cheerio.load(result);
$('body').find('.card-body').each(function(){
print($(this).html());
var cName = $(this).find('.card-title>a').text(),
cURL = $(this).find('.card-title>a').attr('href');
cURL = 'https://segmentfault.com' + cURL;
if(cName === '') return;
log('课程名称:', cName);
log('课程网址:', cURL.trim());
log('');
});
});
});
//$ = cheerio.load(result)将html结构转化为对象,之后的方法去操作对象。
//例如使用find找到的元素依然是以对象的形式存储
//通过使用html()方法可以将对象转化为html结构
//text()方法可以显示该元素渲染后的结构
//常用方法html() find() text() attr()
marked模块
在命令行中
$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>
在浏览器中
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Marked in the browser</title>
</head>
<body>
<div id="content"></div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
document.getElementById('content').innerHTML =
marked('# Marked in the browser\n\nRendered by **marked**.');
</script>
</body>
</html>