update-notifier会异步在背后默默检查npm包的可用最新版。本质就是开了child_process运行在后台,如果检查到有可用更新版,会将结果保存在.update属性中。
notifier = updateNotifier(options):返回一个带有.update属性的实例,如果没有可用的更新版,该属性值为undefined。options支持:
- pkg:object型,name和version是必须属性
- updateCheckInterval:多久检查一次,单位ms,默认值1000 * 60 * 60 * 24(一天)
- callback(error, update):update就是notifier.update属性值
- shouldNotifyInNpmScript:(不太明白有啥用)默认false
notifier.notify([options]):显示通知消息,见下图。options支持:
- defer:等进程exit后显示,默认true
- message:自定义显示的文字
- isGlobal:相当于npm i -g
- boxenOpts:自定义盒子样式,默认{padding: 1, margin: 1, align: ‘center’, borderColor: ‘yellow’, borderStyle: ’round’},详见boxen
const updateNotifier = require('update-notifier'); updateNotifier({ pkg: { name: 'chalk', version: '2.4.0' }, updateCheckInterval: 0 }).notify();
项目中用在cli命令行工具里:
const updateNotifier = require('update-notifier'); const pkg = require('../../package.json'); updateNotifier({ pkg }).notify(); // pkg: { name: 'tool-demo', version: '1.0.0' },如果cli有版本更新,客户端能提示有新版的cli