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
25exports . 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