Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Last active February 18, 2016 03:44
Show Gist options
  • Save pmuellr/7a32c6dc0ab0e029371f to your computer and use it in GitHub Desktop.
Save pmuellr/7a32c6dc0ab0e029371f to your computer and use it in GitHub Desktop.
read some bytes from a file with promises
'use strict'
const fs = require('fs')
// promise-style fs subset (at bottom of this file)
const fsp = requirePromised_fs()
// read 12 bytes of this file, print them, or print error if that happens
readFile(__filename, 12)
.then(s => console.log('read:', s.toString()))
.catch(e => console.log('error:', e))
// return a promise to a Buffer len bytes long of first bytes of fileName
function readFile(fileName, len) {
// allocate a buffer
const buff = new Buffer(len)
// get a promise on the open file
const Δfd = fsp.open(fileName, 'r')
// with the open file ...
return Δfd.then(fd => {
// read the first bytes into buffer
const Δread = fsp.read(fd, buff)
// close the file after reading it
const Δclosed = Δread.then(_ => fsp.close(fd))
// after closing, return read buffer
return Δclosed.then(_ => Δread)
})
}
//-----------------------------------------------------------------------------
function requirePromised_fs () {
return {
open: fsp_open,
read: fsp_read,
close: fsp_close,
}
}
function fsp_open(path, flags) {
return new Promise(fulfiller)
function fulfiller(resolve, reject) {
fs.open(path, flags, function cb (err, fd) {
if (err) return reject(err)
resolve(fd)
})
}
}
function fsp_read(fd, buffer) {
return new Promise(fulfiller)
function fulfiller(resolve, reject) {
fs.read(fd, buffer, 0, buffer.length, 0, function cb (err, bytesRead, bufferR) {
if (err) return reject(err)
resolve(bufferR.slice(0, bytesRead))
})
}
}
function fsp_close(fd) {
return new Promise(fulfiller)
function fulfiller(resolve, reject) {
fs.close(fd, function cb (err) {
if (err) return reject(err)
resolve(null)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment