once

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

Run a function exactly one time

原始使用文档

once

Only call a function once.

usage

var once = require('once')

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

Or add to the Function.prototype in a responsible way:

// 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)
}

Ironically, the prototype feature makes this module twice as complicated as necessary.

To check whether you function has been called, use fn.called. Once the function is called for the first time the return value of the original function is saved in fn.value and subsequent calls will continue to return this 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)

Throw an error if the function is called twice.

Some functions are expected to be called only once. Using once for them would potentially hide logical errors.

In the example below, the greet function has to call the callback only once:

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 是什么?

Run a function exactly one time

如何安装 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 和提交记录判断。