Last active
October 15, 2018 08:14
-
-
Save norbornen/8ff7e20803544b21d232c120ac0777ca to your computer and use it in GitHub Desktop.
node.js stream with promisified reading (vanilla)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const testfile = path.join(path.resolve(), 'test.txt'); | |
read(testfile); | |
async function read(filepath) { | |
const rstream = fs.createReadStream(filepath, {highWaterMark: 70, encoding: 'utf-8'}); | |
let data; | |
let reader = readStream(rstream); | |
while(null !== (data = await reader())) { | |
console.log('data=' + data); | |
} | |
console.log('done'); | |
} | |
function readStream(rstream) { | |
let def; | |
rstream.on('error', (err) => { | |
console.error(err); | |
def && def.resolve(null); | |
}); | |
rstream.on('end', () => def && def.resolve(null)); | |
rstream.on('data', (x) => def && def.resolve(x || '')); | |
return () => { | |
def = deferred(); | |
return def.promise; | |
}; | |
} | |
function deferred() { | |
let resolve; | |
let reject; | |
const promise = new Promise((resolveFn, rejectFn) => { | |
resolve = resolveFn; | |
reject = rejectFn; | |
}); | |
return {promise, resolve, reject}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment