npm库学习

dotenv (读取.env配置文件内配置信息 ) [node]

npm:dotenv
使用:https://blog.csdn.net/inthat/article/details/114685119
代码示例:

import dotenv from 'dotenv'
// dotenv.config()默认获取当前根目录下的.env
// parsed 默认将 key=value 格式转换成obj
const env = dotenv.config().parsed // 环境参数

qrcode-terminal (控制台生成二维码) [node]

npm:qrcode-terminal
使用:https://www.jianshu.com/p/ae102f4a033c
代码示例:

import qrTerminal from 'qrcode-terminal'
qrcode.generate('This will be a QRCode, eh!');

wechaty (自动登录微信,并自定义返回信息,可制作回复机器人)

npm:wechaty
使用:https://blog.csdn.net/qq_34761385/article/details/127734158
代码示例:

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}\nhttps://wechaty.js.org/qrcode/${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
使用:https://blog.csdn.net/qq_42395775/article/details/112797389
描述:
代码示例:

const cheerio = require('cheerio');
 $(`<script>__git=${JSON.stringify({
        remote,
        branch,
        userName  
      })} </script>`).appendTo("head")
$.html()

fs-extra (替换fs操作文件,api友好) [node]

npm:fs-extra
使用:https://www.jianshu.com/p/d1fcc227391c
代码示例:

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
使用:https://blog.csdn.net/weixin_45249263/article/details/123719280
代码示例:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }
}

rimraf (类似clean-webpack-plugin 清除目录) [node]

npm:rimraf
使用:https://blog.csdn.net/qq_35812380/article/details/126330630
描述:
代码示例:

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
使用:https://blog.csdn.net/qq_40122602/article/details/124018596
代码示例:

"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 testing
  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Fred Foo 👻" <foo@example.com>', // sender address
    to: "bar@example.com, baz@example.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main().catch(console.error);

showdown (将markdown 转换成html)

npm:showdown
使用:https://showdownjs.com/
代码示例:

var showdown  = require('showdown'),
 converter = new showdown.Converter(),
 text      = '# hello, markdown!',
 html      = converter.makeHtml(text);

decimal.js (decimal.js是一个科学计算库,可以进行任意精度的十进制运算。)

npm:decimal
使用:http://mikemcl.github.io/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
使用:https://braft.margox.cn/
代码示例:

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 server
    const htmlContent = await fetchEditorContent()
    // Use BraftEditor.createEditorState to convert html strings to editorState data needed by the editor
    this.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 content
    const htmlContent = this.state.editorState.toHTML()
    const result = await saveEditorContent(htmlContent)
  }
 
  handleEditorChange = (editorState) => {
    this.setState({ editorState })
  }
 
  render () {
 
    const { editorState } = this.state
 
    return (
      <div className="my-component">
        <BraftEditor
          value={editorState}
          onChange={this.handleEditorChange}
          onSave={this.submitContent}
        />
      </div>
    )
 
  }
 
}

p-pipe (将promise返回和异步函数组合到可重用的管道中) [node]

npm:p-pipe
使用:https://github.com/sindresorhus/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
使用:https://blog.csdn.net/wade3po/article/details/118676311
描述:原来每个文件的文件字节流开头内容都会有一个文件类型的标记,其实文件字节流就是这个文件,改了后缀名,这个文件字节流的文件类型标记是不会被修改的。file-type可以是被这个标记。
代码示例:

import {fileTypeFromFile} from 'file-type';
console.log(await fileTypeFromFile('Unicorn.png'));

make-dir (创建文件夹) [node]

npm:make-dir
使用:https://www.npmjs.com/package/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
使用:https://www.cnblogs.com/raind/p/10211951.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
使用:https://github.com/sindresorhus/junk#readme
代码示例:

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
使用:https://www.npmjs.com/package/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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥肥呀呀呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值