https://github.com/vweevers/fs-lotus
Sugar to open and close a file descriptor
https://github.com/vweevers/fs-lotus
Last synced: about 1 year ago
JSON representation
Sugar to open and close a file descriptor
- Host: GitHub
- URL: https://github.com/vweevers/fs-lotus
- Owner: vweevers
- License: mit
- Created: 2016-12-11T20:31:55.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2020-12-11T17:47:46.000Z (over 5 years ago)
- Last Synced: 2025-03-28T21:39:05.586Z (about 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 3.91 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
# fs-lotus
**Sugar to open and close a file descriptor.**
[](https://www.npmjs.org/package/fs-lotus) [](https://www.npmjs.org/package/fs-lotus) [](http://travis-ci.org/vweevers/fs-lotus) [](https://ci.appveyor.com/project/vweevers/fs-lotus) [](https://david-dm.org/vweevers/fs-lotus)
## usage
```js
const open = require('fs-lotus')
, fs = require('fs')
const readExactly = function (filename, pos, length, done) {
open(filename, 'r', function (err, fd, close) {
if (err) return done(err)
fs.read(fd, Buffer(length), 0, length, pos, function (err, bytesRead, buf) {
if (err) return close(done, err)
if (bytesRead !== length) {
return close(done, new Error('End of file'))
}
close(done, null, buf)
})
})
}
```
The `open` function has the same signature as [`fs.open(path, flags[, mode], callback)`](https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback). Except that `callback` also receives a `close(callback, err, ...args)` function, which calls `fs.close` for you. An error from `fs.close` (if any) will be [combined](https://github.com/matthewmueller/combine-errors) with your error (if any).
This pattern ensures that our `readExactly` function doesn't leak fd's.
```js
readExactly('readme.md', 0, 10, function (err, buf) {
console.log(buf.toString()) // '# fs-lotus'
})
readExactly('readme.md', 1e5, 10, function (err, buf) {
console.log(err.toString()) // 'Error: End of file'
})
```
## install
With [npm](https://npmjs.org) do:
```
npm install fs-lotus
```
## license
[MIT](http://opensource.org/licenses/MIT) © Vincent Weevers