node

有用的nodejs NPM包

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

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

# 2. validator 是一个字符串验证器和清理器库。

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

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

import * as yup from 'yup'
let schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email(),
  website: yup.string().url(),
  createdOn: yup.date().default(function () {
    return new Date()
  })
})
// check validity
schema
  .isValid({
    name: 'jimmy',
    age: 24
  })
  .then(
    valid => console.log(valid) // => true
  )
// you can try and type cast objects to the defined schema
schema.cast({
  name: 'jimmy',
  age: '24',
  createdOn: '2014-09-23T19:25:25Z'
})
// => { name: 'jimmy', age: 24, createdOn: Date }

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

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

# 5. uuid 是一个用于创建 RFC4122 通用唯一标识符的库。

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

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

const fs = require('fs-extra')
async function copyFiles() {
  try {
    await fs.copy('/tmp/myfile', '/tmp/mynewfile')
    console.log('success!')
  } catch (err) {
    console.error(err)
  }
}
copyFiles()

# 7. mkdirp 递归地创建目录和所有必要的子目录

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

# 8. glob 是一个使用多种模式匹配文件的库。

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

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

const shell = require('shelljs')
if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git')
  shell.exit(1)
}
// Copy files to release dir
shell.rm('-rf', 'out/Release')
shell.cp('-R', 'stuff/', 'out/Release')
// Replace macros in each .js file
shell.cd('lib')
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file)
})
shell.cd('..')
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed')
  shell.exit(1)
}

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

const yaml = require('js-yaml')
const fs = require('fs')
// Get document, or throw exception on error
try {
  const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8'))
  console.log(doc)
} catch (e) {
  console.log(e)
}

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

const winston = require('winston')
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'user-service' },
  transports: [
    // Write all logs with level `error` and below to `error.log`
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    // Write all logs with level `info` and below to `combined.log`
    new winston.transports.File({ filename: 'combined.log' })
  ]
})
logger.log({
  level: 'error',
  message: 'Hello distributed log files!'
})
logger.info('Hello again distributed logs')

# 13. debug

const debug = require('debug')('http'),
  http = require('http'),
  name = 'My App'
debug('booting %o', name)
http
  .createServer(function (req, res) {
    debug(req.method + ' ' + req.url)
    res.end('hello\n')
  })
  .listen(3000, function () {
    debug('listening')
  })

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

.env file:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
require('dotenv').config();
const db = require('db');
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
});

# 15. semver 版本号

npm (opens new window)

# 16. real-ip 获取真实 ip

export const real_ip = () =>
  new Promise((resolve, reject) => {
    let timer = null
    timer ?? clearInterval(timer)
    getIPs(ip => {
      resolve(ip)
    })
    timer = setInterval(() => {
      reject('时间过长')
    }, 2000)
  })
上次更新: