1.0.0 • Published 9 years ago
fs-maybe-open v1.0.0
fs-maybe-open
Open a file unless it's already a file descriptor.
usage
const maybeOpen = require('fs-maybe-open')
, fs = require('fs')
function readExactly(fdOrFile, pos, length, done) {
maybeOpen(fdOrFile, 'r', function (err, fd, maybeClose) {
if (err) return done(err)
fs.read(fd, Buffer(length), 0, length, pos, function (err, bytesRead, buf) {
if (err) return maybeClose(done, err)
if (bytesRead !== length) {
return maybeClose(done, new Error('End of file'))
}
maybeClose(done, null, buf)
})
})
}The maybeOpen function has the same signature as fs.open(path, flags[, mode], callback). Except:
- If
pathis a file descriptor, opening is a noop - The open
callbackalso receives amaybeClose(callback, err, ...args)function, which callsfs.closefor you ifpathwas a filename. An error fromfs.close(if any) will be combined with your error (if any).
install
With npm do:
npm install fs-maybe-openlicense
MIT © Vincent Weevers
1.0.0
9 years ago