Node.js 常用软件包
1. Chalk
Chalk, 在终端设置输出样式
在开发新的Node.js应用程序期间 console.log 必不可少,不管我们用它来输出错误、系统数据还是函数和co的输出。但是,这确实会造成一些混乱,因为默认情况下 console.log 函数在终端中输出纯白色文本。 使用Chalk可以改变了这一点。
安装
yarn add chalk // 或者 npm install chalk
示例代码
// chalkDemo.js
const chalk = require("chalk")
// just blue font
console.log(chalk.blue("this is list"))
// blue & bold font, red background (bg = background)
console.log(chalk.blue.bgRed.bold("Blue & Bold on Red"))
// blue font, red background
console.log(chalk.blue.bgRed("Regular Blue on Red"))
// combining multiple font colors
console.log(chalk.blue("Blue") + "Default" + chalk.red("Red"))
// Underlining text
console.log(chalk.red("There is an ", chalk.underline("Error")))
// Using RGB-colors
console.log(chalk.rgb(127, 255, 0).bold("Custom green"))
输出结果可能如下:
2. Morgan
Morgan, 记录HTTP请求中的所有重要信息
安装
yarn add morgan // 或者 npm install morgan
示例代码
// morganDemo.js
const express = require('express')
const morgan = require('morgan')
const app = express()
app.use(
morgan(':method :url :status :response-time ms')
)
app.get('/', function(req, res){
res.send('hello jameszhang');
})
app.listen(8001);
浏览器打开http://localhost:8001, 即可看到输出结果如下:
3. cheerio
cheerio, 使用类似jQuery的语法处理服务器上已经存在的DOM.
当我们需要提供动态HTML模板(非静态HTML文件)时, cheerio非常有用. 我们可以在浏览器的请求和响应之间直接修改请求的HTML代码, 而客户端并不知情. 由于类似jQuery的语法, 学习起来很简单. 当然, 你也可以使用cheerio做爬虫和其他许多操作.
安装
yarn add cheerio // 或者 npm install cheerio
示例代码
const cheerio = require('cheerio')
let template = `
<div id="demo">
<h3 class="content">Hello world!</h3>
<h3 class="content">Hello james!</h3>
</div>
`
const $ = cheerio.load(template)
console.log($('h3').text())
// 追加子元素
$('div').append("<p class='demo'>demo</p>")
// 重新赋值
template = $.html()
console.log(template)