-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbatch.js
55 lines (47 loc) · 1.69 KB
/
batch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict'
const util = require('util');
const stream = require('stream');
const fs = require('fs');
const CsvReadableStream = require('csv-reader');
const filter = require("stream-filter");
/** understand/
* We need a way to process each row in a file which contains batch operations/accounts
* synchronously since we do not want multiple stellar operations to run concurrently.
* Therefore we introduce a Stream processor which uses pause/resume and a the resolution
* of a promise to achieve this synchronous processing.
*/
function RowProcessor(processFn, options) {
// allow use without new
if (!(this instanceof RowProcessor)) {
return new RowProcessor(processFn, options);
}
this.processorFn = processFn;
// init Transform
if (!options) options = {}; // ensure object
options.objectMode = true; // forcing object mode
stream.Transform.call(this, options);
}
util.inherits(RowProcessor, stream.Transform);
RowProcessor.prototype._transform = function (obj, enc, cb) {
this.pause();
this.processorFn(obj, (err, res) => {
if (err) throw new Error(err);
this.push(res);
cb();
this.resume();
});
};
/**
* way/
* To support commenting out lines in batch files we use a stream filter which removes lines starting with `#`
*/
const commentFilter = filter.obj(line => !line[0].startsWith('#'));
function processCSVFile(csvFile, processorFn) {
return fs.createReadStream(csvFile, 'utf8')
.pipe(CsvReadableStream({ parseNumbers: true, parseBooleans: true, trim: true }))
.pipe(commentFilter)
.pipe(RowProcessor(processorFn));
}
module.exports = {
processCSVFile: processCSVFile
};