• JS基础:常用的Node.js NPM 包


    1. qs

    一个简单易用的字符串解析和格式化库

    1. const qs = require('qs');
    2. const assert = require('assert');
    3. const obj = qs.parse('a=c');
    4. assert.deepEqual(obj, { a: 'c' });
    5. const str = qs.stringify(obj);
    6. assert.equal(str, 'a=c');

    2.rxjs

    RxJS是一组模块化的库,用于使用 JavaScript 中的可观察集合和组合来组合异步和基于事件的程序。

    1. const { range } = require('rxjs');
    2. const { map, filter } = require('rxjs/operators');
    3. range(1, 200).pipe(
    4. filter(x => x % 2 === 1),
    5. map(x => x + x)
    6. ).subscribe(x => console.log(x));

    3. mitt

    微型 200b 功能事件发射器/发布订阅.

    1. import mitt from 'mitt'
    2. const emitter = mitt()
    3. emitter.on('foo', e => console.log('foo', e) )
    4. emitter.on('*', (type, e) => console.log(type, e) )
    5. emitter.emit('foo', { a: 'b' })
    6. emitter.all.clear()
    7. function onFoo() {}
    8. emitter.on('foo', onFoo) // listen
    9. emitter.off('foo', onFoo) // unlisten

    4.Underscore.js

    Underscore.js是一个用于 JavaScript 的实用程序带库,它在不扩展任何核心 JavaScript 对象的情况下为通常的功能嫌疑人(each、map、reduce、filter 等)提供支持。

    1. const _ = require('underscore');
    2. const list = [[5, 1, 7], [3, 2, 1]];
    3. _.invoke(list, 'sort');
    4. // => [[1, 5, 7], [1, 2, 3]]

    5.day.js

    Day.js是一个极简主义的 JavaScript 库,它为现代浏览器解析、验证、操作和显示日期和时间,并具有很大程度上与 Moment 兼容的 API。

    1. const dayjs = require('dayjs');
    2. dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss');

    6.ramda

    Ramda是一个实用的函数式库,具有可与柯里化组合的无副作用函数。

    1. import * as R from 'ramda';
    2. const double = x => x * 2;
    3. R.map(double, [1, 2, 3]);
    4. // => [2, 4, 6]
    5. R.map(double, {x: 1, y: 2, z: 3});
    6. // => {x: 2, y: 4, z: 6}

    7.validator

    Validator是一个字符串验证器和清理器库。

    1. var validator = require('validator');
    2. validator.isEmail('foo@bar.com'); //=> true

    8.yup

    yup是一个用于复杂的、相互依赖的验证和转换的模式构建器。

    1. import * as yup from 'yup';
    2. let schema = yup.object().shape({
    3. name: yup.string().required(),
    4. age: yup.number().required().positive().integer(),
    5. email: yup.string().email(),
    6. website: yup.string().url(),
    7. createdOn: yup.date().default(function () {
    8. return new Date();
    9. }),
    10. });
    11. // check validity
    12. schema
    13. .isValid({
    14. name: 'jimmy',
    15. age: 24,
    16. })
    17. .then(valid =>
    18. console.log(valid) // => true
    19. );
    20. // you can try and type cast objects to the defined schema
    21. schema.cast({
    22. name: 'jimmy',
    23. age: '24',
    24. createdOn: '2014-09-23T19:25:25Z',
    25. });
    26. // => { name: 'jimmy', age: 24, createdOn: Date }

    9.lodash

    Lodash是一个实用程序库,通过消除处理数组、数字、对象、字符串等的麻烦,使 JavaScript 变得更容易。

    1. const _ = require('lodash');
    2. const nums = _.range(1, 9);
    3. // => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    4. const chunks = _.chunk(nums, 3);
    5. // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    6. const right = _.takeRight(nums, 2);
    7. // => [7, 8, 9]

    10.date-fns

    Date-fns提供了最全面、最简单且一致的工具集,用于在浏览器和 Node.js 中操作 JavaScript 日期。

    1. import { format, formatDistance, formatRelative, subDays } from 'date-fns'
    2. format(new Date(), '[Today is a] dddd')
    3. //=> "Today is a Wednesday"
    4. formatDistance(subDays(new Date(), 3), new Date())
    5. //=> "3 days ago"
    6. formatRelative(subDays(new Date(), 3), new Date())
    7. //=> "last Friday at 7:26 p.m."

    11.jsonwebtoken

    Jsonwebtoken是一个用于对 JSON Web 令牌进行签名、验证和解码的库。

    1. const jwt = require('jsonwebtoken');
    2. const token = jwt.sign({ foo: 'bar' }, 'shhhhh');

    12.uuid

    UUID 是一个用于创建 RFC4122 通用唯一标识符的库。

    1. const { v4: uuidv4 } = require('uuid');
    2. uuidv4(); // => '1a68a438-b077-468b-b1e8-dcdd976a0f5b'

    二、操作文件系统

    1.rimraf

    Rimraf 为节点提供了与 UNIX rm -rf 命令等效的命令。

    1. const rimraf = require('rimraf');
    2. rimraf('./build', error => {
    3. if (error) console.error(error);
    4. });

    2.fs-extra

    FS-extra 添加了未包含在本机 fs 模块中的文件系统方法,并为 fs 方法添加了 promise 支持。

    1. const fs = require('fs-extra');
    2. async function copyFiles () {
    3. try {
    4. await fs.copy('/tmp/myfile', '/tmp/mynewfile');
    5. console.log('success!');
    6. } catch (err) {
    7. console.error(err);
    8. }
    9. }
    10. copyFiles();

    3.mkdirp

    就像 mkdir -p 一样,mkdirp 递归地创建目录和所有必要的子目录。

    1. const mkdirp = require('mkdirp')
    2. // return value is a Promise resolving to the first directory created
    3. mkdirp('/tmp/foo/bar/baz').then(made =>
    4. console.log(`made directories, starting with ${made}`));

    4.glob

    Glob 是一个使用多种模式匹配文件的库。

    1. const glob = require('glob');
    2. // options is optional
    3. glob("**/*.js", options, function (er, files) {
    4. // files is an array of filenames.
    5. // If the `nonull` option is set, and nothing
    6. // was found, then files is ["**/*.js"]
    7. // er is an error object or null.
    8. });

    5.shelljs

    ShellJS 是基于 Node.js API 的 Unix shell 命令的可移植 (Windows/Linux/OS X) 实现。

    1. const shell = require('shelljs');
    2. if (!shell.which('git')) {
    3. shell.echo('Sorry, this script requires git');
    4. shell.exit(1);
    5. }
    6. // Copy files to release dir
    7. shell.rm('-rf', 'out/Release');
    8. shell.cp('-R', 'stuff/', 'out/Release');
    9. // Replace macros in each .js file
    10. shell.cd('lib');
    11. shell.ls('*.js').forEach(function (file) {
    12. shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
    13. shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
    14. shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
    15. });
    16. shell.cd('..');
    17. // Run external tool synchronously
    18. if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
    19. shell.echo('Error: Git commit failed');
    20. shell.exit(1);
    21. }

    6.js-yaml

    Js-yaml 是 YAML 的一种实现,YAML 是一种流行的人性化数据序列化语言。

    1. const yaml = require('js-yaml');
    2. const fs = require('fs');
    3. // Get document, or throw exception on error
    4. try {
    5. const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
    6. console.log(doc);
    7. } catch (e) {
    8. console.log(e);
    9. }

    三、Web框架

    1. koa

    Koa 是由 Express 背后的团队设计的新 Web 框架,旨在成为 Web 应用程序和 API 的更小、更具表现力和更健壮的基础。

    1. const Koa = require('koa');
    2. const app = new Koa();
    3. app.use(async ctx => {
    4. ctx.body = 'Hello World';
    5. });
    6. app.listen(3000);

    2. express

    Express.js 是最流行、最快速、最简约的 node.js 后端 Web 框架。

    1. const express = require('express');
    2. const app = express();
    3. app.get('/', function (req, res) {
    4. res.send('Hello World');
    5. });
    6. app.listen(3000);

    3. Fastify

    Fastify是最快的可扩展 Web 框架之一,专注于以最少的开销提供最佳的开发人员体验。

    1. const fastify = require('fastify')({
    2. logger: true
    3. });
    4. fastify.get('/', async (request, reply) => {
    5. reply.type('application/json').code(200);
    6. return { hello: 'world' };
    7. });
    8. fastify.listen(3000, (err, address) => {
    9. if (err) throw err;
    10. fastify.log.info(`App listening on ${address}`);
    11. });

    4. socket.io

    Socket.IO使用长轮询或 WebSockets 启用实时双向基于事件的通信,并具有断开连接检测和自动重新连接支持。

    1. const server = require('http').createServer();
    2. const io = require('socket.io')(server);
    3. io.on('connection', client => {
    4. client.on('event', data => { /* … */ });
    5. client.on('disconnect', () => { /* … */ });
    6. });
    7. server.listen(3000);

    四、辅助开发

    1. jest

    Jest 已完成并准备好设置 JavaScript 测试解决方案

    1. test('adds 1 + 2 to equal 3', () => {
    2. expect(1 + 2).toBe(3);
    3. });

    2. typescript

    TypeScript 是可扩展的 JavaScript。 它是一种添加可选类型并编译为普通可读 JavaScript 的语言。

    1. interface User {
    2. name: string;
    3. id: number;
    4. }
    5. const user: User = {
    6. name: "Hayes",
    7. id: 0,
    8. };

    3.winston

    Winston 是一个简单且通用的日志库,支持多种传输。

    1. const winston = require('winston');
    2. const logger = winston.createLogger({
    3. level: 'info',
    4. format: winston.format.json(),
    5. defaultMeta: { service: 'user-service' },
    6. transports: [
    7. // Write all logs with level `error` and below to `error.log`
    8. new winston.transports.File({ filename: 'error.log', level: 'error' }),
    9. // Write all logs with level `info` and below to `combined.log`
    10. new winston.transports.File({ filename: 'combined.log' }),
    11. ],
    12. });
    13. logger.log({
    14. level: 'error',
    15. message: 'Hello distributed log files!'
    16. });
    17. logger.info('Hello again distributed logs');

    4.debug

    Debug 是一个微型 JavaScript 调试实用程序,模仿 Node.js 核心的调试技术。

    1. const debug = require('debug')('http')
    2. , http = require('http')
    3. , name = 'My App';
    4. debug('booting %o', name);
    5. http.createServer(function(req, res){
    6. debug(req.method + ' ' + req.url);
    7. res.end('hello\n');
    8. }).listen(3000, function(){
    9. debug('listening');
    10. });

    5. eslint

    ESLint 是一种用于查找和修复 JavaScript 和 TypeScript 代码中问题的工具。

    1. {
    2. "rules": {
    3. "semi": ["error", "always"],
    4. "quotes": ["error", "double"]
    5. }
    6. }

    6. nodemon

    Nodemon 是一个工具,它通过在检测到目录中的文件更改时自动重新启动节点应用程序来帮助开发基于 node.js 的应用程序。

    nodemon ./server.js 

    7. dotenv

    Dotenv 是一个零依赖模块,可将 .env 文件中的环境变量加载到 process.env中

    1. .env file:
    2. DB_HOST=localhost
    3. DB_USER=root
    4. DB_PASS=s1mpl3
    5. require('dotenv').config();
    6. const db = require('db');
    7. db.connect({
    8. host: process.env.DB_HOST,
    9. username: process.env.DB_USER,
    10. password: process.env.DB_PASS
    11. });

    8. cross-env

    Cross-env 使脚本能够跨平台设置和使用环境变量

    1. {
    2. "scripts": {
    3. "start-prod": "cross-env NODE_ENV=production node ./app.js"
    4. }
    5. }

     转载地址:30 个有用的 Node.js NPM 包 - 掘金

  • 相关阅读:
    【接口自动化测试入门】接口测试基础(超详细~)
    Spring MVC文件上传配置
    驱动开发5 阻塞IO实例、IO多路复用
    【JUC系列-08】深入理解CyclicBarrier底层原理和基本使用
    如何高效的分析online.log
    9个值得收藏的WebGL性能优化技巧
    Java框架详解3——Spring的存入对象和取出
    FreePascal 解析命令行参数
    【Rust日报】用Rust从头实现一个C编译器
    mysql自动备份脚本开发,包含自动清理备份文件机制
  • 原文地址:https://blog.csdn.net/m0_63748493/article/details/127132377