once

中文文档
1.4.0发布于 2016/09/07ISCCommonJS近 30 天下载 6.8亿

只运行一个函数一次

中文使用文档

一次

只调用一个函数一次。

用法

var once = require('once')

function load (file, cb) {
  cb = once(cb)
  loader.load('file')
  loader.once('load', cb)
  loader.once('error', cb)
}

或者添加到函数中。以负责任的方式制作原型:

// only has to be done once
require('once').proto()

function load (file, cb) {
  cb = cb.once()
  loader.load('file')
  loader.once('load', cb)
  loader.once('error', cb)
}

具有讽刺意味的是,原型特性使这个模块成为 尽可能复杂。

要检查函数是否已被调用,请使用 fn.called. 一旦 函数第一次调用时返回原函数的返回值 函数保存在 fn.value 随后的电话将继续 返回此值。

var once = require('once')

function load (cb) {
  cb = once(cb)
  var stream = createStream()
  stream.once('data', cb)
  stream.once('end', function () {
    if (!cb.called) cb(new Error('not found'))
  })
}

once.strict(func)

如果函数被调用两次,则抛出错误。

有些函数只被调用一次。使用 once 因为他们会 潜在地隐藏逻辑错误。

在下面的示例中, greet 函数只能调用回调一次:

function greet (name, cb) {
  // return is missing from the if statement
  // when no name is passed, the callback is called twice
  if (!name) cb('Hello anonymous')
  cb('Hello ' + name)
}

function log (msg) {
  console.log(msg)
}

// this will print 'Hello anonymous' but the logical error will be missed
greet(null, once(msg))

// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time
greet(null, once.strict(msg))

版本与发布记录

once 共发布 7 个版本,首次发布于 2012/08/14;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.4.0latest2016/09/0710 年前
1.3.32015/11/2110 年前
1.3.22015/05/0511 年前
1.3.12014/09/1912 年前
1.3.02013/10/2413 年前
1.2.02013/08/1213 年前

关于 once 的常见问题

once 是什么?

只运行一个函数一次

如何安装 once?

在项目目录运行 npm install once,或使用 pnpm add / yarn add / bun add。

once 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/once 是否存在。

once 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

once 可以商用吗?

once 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

once 的下载量有多少?

根据 npm 官方下载统计,once 在 2026/10/05 – 2026/11/03 这 30 天内被下载 682,857,767 次,日均约 22,761,926 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

once 还在维护吗?

最新版本 1.4.0 发布于 2016/09/07(10 年前);至今共发布 7 个版本,其中过去 12 个月发布了 0 个;首次发布于 2012/08/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。