Skip to content

Commit bb9a28f

Browse files
committed
feat: 🎸 add file/stream utils
1 parent 514fdda commit bb9a28f

2 files changed

Lines changed: 45 additions & 1 deletion

File tree

test/utils.test.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const test = require('./config')
2-
const { isNil, mergeArray } = require('../utils')
2+
const { isNil, mergeArray, err2cb } = require('../utils')
33

44
test('isNil is true for null or undefined', t=>{
55
t.is(isNil(undefined), true)
@@ -38,3 +38,10 @@ test('take the 1st array when both are of equal length', t => {
3838
test('take the 1st array when the 2nd has smaller length', t => {
3939
t.deepEqual(mergeArray([1,3], [2]), [1,3])
4040
})
41+
42+
43+
test('err2cb preserves cps function without errors', t=>{
44+
err2cb(c=>c(2))(t.cis(2))
45+
})
46+
47+

utils.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
const fs = require('node:fs')
2+
const { createInterface } = require('node:readline')
3+
14
// true if and only if the value is null or undefined
25
exports.isNil = x => undefined === x || null === x
36

@@ -12,3 +15,37 @@ exports.inheritPrototype = (target, source) => {
1215
Object.getPrototypeOf(source)
1316
)
1417
}
18+
19+
/**
20+
* Send syncronous errors into nth callback of CPS function.
21+
* Defaults to n = 2.
22+
*
23+
* @param {Function} cpsF - CPS function
24+
* @param [{Number} n] - number of the callback
25+
* @returns {Function} cpsF - CPS function receiving sync errors into its nth callback
26+
*/
27+
exports.err2cb = (cpsF, n=2) => (...cbs) =>
28+
{ try {return cpsF(...cbs)} catch(err) {return cbs[n-1](err)} }
29+
30+
31+
32+
// ---- File/Stream utils ---- //
33+
34+
/**
35+
* Transform file path into Node stream of the file content
36+
* based on `fs.createReadStream`
37+
* https://nodejs.org/api/fs.html#fscreatereadstreampath-options
38+
*/
39+
exports.file2stream = fs.createReadStream
40+
41+
/**
42+
* Transform Readable Node stream to CPS function with 3 callbacks (onRes, onErr, onEnd):
43+
* - onRes receives content of each line from stream;
44+
* - onErr receives errors;
45+
* - onEnd receives `null` when stream ends.
46+
*
47+
* @param {Stream} input - Readable Node stream
48+
* @returns {Function} - CPS function
49+
*/
50+
exports.stream2lines = input => (onRes, onErr, onEnd) =>
51+
{try {createInterface(input).on('line', onRes).on('close', _ => onEnd(null))} catch(err) {onErr(err)}}

0 commit comments

Comments
 (0)