Xervo

npm Install Once

npm Install Once

Once is one of my favorite modules I use, it shows up in almost all the applications I write, created by Isaac Schlueter. It’s a very simple idea. Once takes a function and returns a function that will call the function you passed it, only once. If you try to call it more then once, the subsequent calls will simply be noops.

var once = require(‘once’)

function myAPI (cb) {
  cb = once(cb)
  // my code
}

Other that protect you from the more obvious double-callback errors this also allows you to more safely attach the callback handler directly to event emitters and streams where appropriate.

function (cb) {
  cb = once(cb)
  var stream = createReadableStream()
  stream.on(‘data’, { /* do stuff with data */ })
  stream.on(‘end’, cb)
  stream.on(‘error’, cb)
}

According to the spec, a readable stream should only end or error once. In practice many streams don’t check properly for this and may error long after ending cleanly or call end after erroring. This protects you from these bugs without forcing you to implement your own checks. Simple modules like once are what make programming in Node fun and easy.

What is Xervo?

Xervo makes deploying applications in the public cloud or your own data center easy. Node.js, PHP, Java, Python, Nginx, and MongoDB supported. Full Docker support included in Enterprise version. It’s free to get started.

Share This Article

comments powered by Disqus