npm库学习"/>
npm库学习
dotenv
(读取.env配置文件内配置信息 ) [node]
npm:dotenv
使用:
代码示例:
import dotenv from 'dotenv'
// dotenv.config()默认获取当前根目录下的.env
// parsed 默认将 key=value 格式转换成obj
const env = dotenv.config().parsed // 环境参数
qrcode-terminal
(控制台生成二维码) [node]
npm:qrcode-terminal
使用:
代码示例:
import qrTerminal from 'qrcode-terminal'
qrcode.generate('This will be a QRCode, eh!');
wechaty
(自动登录微信,并自定义返回信息,可制作回复机器人)
npm:wechaty
使用:
代码示例:
import { WechatyBuilder } from 'wechaty'
const wechaty = WechatyBuilder.build() // get a Wechaty instance
wechaty.on('scan', (qrcode, status) => console.log(`Scan QR Code to login: ${status}\n/${encodeURIComponent(qrcode)}`)).on('login', user => console.log(`User ${user} logged in`)).on('message', message => console.log(`Message: ${message}`))
wechaty.start()
cheerio
(解析DOM 然后对dom进行操作)
npm:cheerio
使用:
描述:
代码示例:
const cheerio = require('cheerio');$(`<script>__git=${JSON.stringify({remote,branch,userName })} </script>`).appendTo("head")
$.html()
fs-extra
(替换fs操作文件,api友好) [node]
npm:fs-extra
使用:
代码示例:
const fse = require('fs-extra')
// 同步
try {fs.copySync('/tmp/myfile', '/tmp/mynewfile')console.log('success!')
} catch (err) {console.error(err)
}// 异步 promise
fs.copy('/tmp/myfile', '/tmp/mynewfile').then(() => console.log('success!')).catch(err => console.error(err))// 异步回调
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {if (err) return console.error(err)console.log('success!')
})async function copyFiles () {try {await fs.copy('/tmp/myfile', '/tmp/mynewfile')console.log('success!')} catch (err) {console.error(err)}
}
copyFiles()
cross-env
(命令行,进行配置环境变量) [node]
npm:cross-env
使用:
代码示例:
{"scripts": {"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"}
}
rimraf
(类似clean-webpack-plugin 清除目录) [node]
npm:rimraf
使用:
描述:
代码示例:
import rimraf from 'rimraf'
rimraf(f, [opts]) -> Promise
This first parameter is a path or array of paths. The second argument is an options object.
// 命令行
rimraf 目录地址
nodemailer
( 发送邮件) [node]
npm:nodemailer
使用:
代码示例:
"use strict";
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
async function main() {// Generate test SMTP service account from ethereal.email// Only needed if you don't have a real mail account for testinglet testAccount = await nodemailer.createTestAccount();// create reusable transporter object using the default SMTP transportlet transporter = nodemailer.createTransport({host: "smtp.ethereal.email",port: 587,secure: false, // true for 465, false for other portsauth: {user: testAccount.user, // generated ethereal userpass: testAccount.pass, // generated ethereal password},});// send mail with defined transport objectlet info = await transporter.sendMail({from: '"Fred Foo 👻" <foo@example>', // sender addressto: "bar@example, baz@example", // list of receiverssubject: "Hello ✔", // Subject linetext: "Hello world?", // plain text bodyhtml: "<b>Hello world?</b>", // html body});console.log("Message sent: %s", info.messageId);// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example>// Preview only available when sending through an Ethereal accountconsole.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));// Preview URL: /message/WaQKMgKddxQDoou...
}
main().catch(console.error);
showdown
(将markdown 转换成html)
npm:showdown
使用:/
代码示例:
var showdown = require('showdown'),converter = new showdown.Converter(),text = '# hello, markdown!',html = converter.makeHtml(text);
decimal.js
(decimal.js是一个科学计算库,可以进行任意精度的十进制运算。)
npm:decimal
使用:.js/
代码示例:
import Decimal from 'decimal.js';
x = new Decimal(123.4567)
y = new Decimal('123456.7e-3')
z = new Decimal(x)
x.equals(y) && y.equals(z) && x.equals(z)
braft-editor
(braft-editor是一个基于React的富文本编辑器,完成度极高,开箱即用!)
npm:braft-editor
使用:/
代码示例:
import React from 'react'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'export default class EditorDemo extends React.Component {state = {editorState: null}async componentDidMount () {// Assume here to get the editor content in html format from the serverconst htmlContent = await fetchEditorContent()// Use BraftEditor.createEditorState to convert html strings to editorState data needed by the editorthis.setState({editorState: BraftEditor.createEditorState(htmlContent)})}submitContent = async () => {// Pressing ctrl + s when the editor has focus will execute this method// Before the editor content is submitted to the server, you can directly call editorState.toHTML () to get the HTML contentconst htmlContent = this.state.editorState.toHTML()const result = await saveEditorContent(htmlContent)}handleEditorChange = (editorState) => {this.setState({ editorState })}render () {const { editorState } = this.statereturn (<div className="my-component"><BraftEditorvalue={editorState}onChange={this.handleEditorChange}onSave={this.submitContent}/></div>)}}
p-pipe
(将promise返回和异步函数组合到可重用的管道中) [node]
npm:p-pipe
使用:
代码示例:
import pPipe from 'p-pipe';const addUnicorn = async string => `${string} Unicorn`;
const addRainbow = async string => `${string} Rainbow`;const pipeline = pPipe(addUnicorn, addRainbow);console.log(await pipeline('❤️'));
file-type
(判断文件类型的库) [node]
npm:file-type
使用:
描述:原来每个文件的文件字节流开头内容都会有一个文件类型的标记,其实文件字节流就是这个文件,改了后缀名,这个文件字节流的文件类型标记是不会被修改的。file-type可以是被这个标记。
代码示例:
import {fileTypeFromFile} from 'file-type';
console.log(await fileTypeFromFile('Unicorn.png'));
make-dir
(创建文件夹) [node]
npm:make-dir
使用:
描述:promise创建文件夹
代码示例:
const makeDir = require('make-dir');
(async () => {const path = await makeDir('unicorn/rainbow/cake');console.log(path);//=> '/Users/sindresorhus/fun/unicorn/rainbow/cake'
})();
globby
(使用规则来匹配文件) [node]
npm:make-dir
使用:.html
代码示例:
import { globby } from "globby";
import path from "node:path";
console.log("globby", await globby(path.resolve(process.cwd(),"../.yc.config.*"),{// expandDirectories: {// extensions: ['*']// }onlyFiles: true
}))
junk
(过滤掉系统垃圾文件,如.DS_Store和Thumbs.db) [node]
npm:junk
使用:
代码示例:
import fs from 'node:fs/promises';
import {isNotJunk} from 'junk';
const files = await fs.readdir('some/path');
console.log(files);
//=> ['.DS_Store', 'test.jpg']
console.log(files.filter(isNotJunk));
replace-ext
(路径字符串替换后缀) [node]
npm:replace-ext
使用:
代码示例:
var replaceExt = require('replace-ext');var path = '/some/dir/file.js';
var newPath = replaceExt(path, '.coffee');console.log(newPath); // /some/dir/file.coffee
更多推荐
npm库学习
发布评论