/
NDJSONCollection.ts
243 lines (223 loc) · 7.78 KB
/
NDJSONCollection.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/// <reference path="../index.d.ts" />
import { writeFileSync } from "fs";
import Collection from "./Collection";
import { filterFiles, readLine } from "./lib";
/**
* This class represents an NDJSON object. An instance can be created from
* different kinds of input using the static methods starting with `from` and
* converted to other kinds of output using the instance methods starting with
* `to`. This class is designed to handle large files or directories by using
* iterators and reading files one line at a time.
*/
export default class NDJSONCollection extends Collection
{
/**
* If we have the entire ndjson as a string, we can create an instance
* of NDJSON which will provide the `lines` and `entries` iterators like so:
* ```js
* const ndjson = NDJSON.fromString("{}\n{}");
* ndjson.lines(); // Lines iterator
* ndjson.entries(); // JSON iterator
* ```
* @param input The input string that can be parsed as JSON
*/
public static fromString(input: string): NDJSONCollection
{
const lines = input.split(/\r?\n/);
const out = new NDJSONCollection();
const entries = lines.map(l => JSON.parse(l));
out.setLines(() => entries.map(o => JSON.stringify(o)).values());
out.setEntries(() => entries.values());
return out;
}
/**
* If we happen to have the entire ndjson as array, we can create an NDJSON
* instance like so:
* ```js
* const ndjson = NDJSON.fromArray([ {}, {} ]);
* ndjson.lines(); // Lines iterator
* ndjson.entries(); // JSON iterator
* ```
* @param arr An array of objects that can be serialized as JSON
*/
public static fromArray(arr: BulkDataTools.IAnyObject[]): NDJSONCollection
{
const out = new NDJSONCollection();
const lines = arr.map(l => JSON.stringify(l));
out.setLines(() => lines.values());
out.setEntries(() => arr.values());
return out;
}
/**
* If we have the entire ndjson as array of strings, we can create an NDJSON
* instance like so:
* ```js
* const ndjson = NDJSON.fromStringArray(["{}", "{}" ]);
* ndjson.lines(); // Lines iterator
* ndjson.entries(); // JSON iterator
* ```
* @param arr An array of strings that can be parsed as JSON
*/
public static fromStringArray(arr: string[]): NDJSONCollection
{
const out = new NDJSONCollection();
const entries = arr.map(l => JSON.parse(l));
out.setLines(() => entries.map(o => JSON.stringify(o)).values());
out.setEntries(() => entries.values());
return out;
}
/**
* Creates and returns an NDJSON instance from directory path. This will
* walk (recursively) through the directory and collect all the files having
* a `.ndjson` extension. The `lines` and `entries` iterators will yield
* results from all those files combined. Example:
* ```js
* const ndjson = NDJSON.fromDirectory("/path/to/directory/containing/ndjson/files");
* ndjson.lines(); // Lines iterator
* ndjson.entries(); // JSON iterator
* ```
* @param path Absolute path to directory
*/
public static fromDirectory(path: string): NDJSONCollection
{
const out = new NDJSONCollection();
function *lines(): IterableIterator<string>
{
const files = filterFiles(path, /\.ndjson$/i);
for (const filePath of files) {
try {
const ndjson = NDJSONCollection.fromFile(filePath);
const _lines = ndjson.lines();
for (const line of _lines) {
yield line;
}
} catch (e) {
throw new Error(`File: ${filePath} - ${e}`);
}
}
}
function *entries(): IterableIterator<BulkDataTools.IAnyObject>
{
const files = filterFiles(path, /\.ndjson$/i);
for (const filePath of files) {
try {
const ndjson = NDJSONCollection.fromFile(filePath);
const _entries = ndjson.entries();
for (const entry of _entries) {
yield entry;
}
} catch (e) {
throw new Error(`File: ${filePath} - ${e}`);
}
}
}
out.setLines(lines);
out.setEntries(entries);
return out;
}
/**
* Creates and returns an NDJSON instance from a file path. Example:
* ```js
* const ndjson = NDJSON.fromFile("/path/to/file.ndjson");
* ndjson.lines(); // Lines iterator
* ndjson.entries(); // JSON iterator
* ```
* @param path Absolute path to NDJSON file
*/
public static fromFile(path: string): NDJSONCollection
{
function *lines(): IterableIterator<string>
{
const _lines = readLine(path);
for (let line of _lines) {
line = line.trim();
// if (line) {
yield JSON.stringify(JSON.parse(line));
// }
}
}
function *entries(): IterableIterator<BulkDataTools.IAnyObject>
{
const _lines = readLine(path);
for (const line of _lines) {
yield JSON.parse(line.trim());
}
}
const out = new NDJSONCollection();
out.setLines(lines);
out.setEntries(entries);
return out;
}
// =========================================================================
// Output Methods
// =========================================================================
/**
* Returns a string representation of the NDJSON object.
* **NOTE:** The string takes memory. Don't use this for big NDJSON objects.
* Use the `lines` or `entries` iterators instead to handle one entry at a time.
*/
public toString(): string
{
let out = "";
for (const line of this._lines()) {
out += (out ? "\r\n" : "") + line;
}
return out;
}
/**
* Returns an array of JSON strings representing of the NDJSON object.
* **NOTE:** The array takes memory. Don't use this for big NDJSON objects.
* Use the `lines` or `entries` iterators instead to handle one entry at a time.
*/
public toStringArray(): string[]
{
const out = [];
for (const line of this._lines()) {
out.push(line);
}
return out;
}
/**
* Returns an array of JSON objects representing of the NDJSON object.
* **NOTE:** The array takes memory. Don't use this for big NDJSON objects.
* Use the `lines` or `entries` iterators instead to handle one entry at a time.
*/
public toArray(): BulkDataTools.IAnyObject[]
{
return [...this.entries()];
}
/**
* Writes the NDJSON object to file. The file can be (re)created or appended
* to. Example:
* ```js
* const ndjson = NDJSON.fromStringArray(["{}", "{}" ]);
*
* // Create or overwrite the file with default settings
* ndjson.toFile("/my/output.ndjson");
*
* // Or use custom settings:
* ndjson.toFile("/my/output.ndjson", {
* eol: "\r\n",
* append: true
* });
* ```
*/
public toFile(path: string, options: any = {}): NDJSONCollection
{
if (!options.append) {
writeFileSync(path, "");
}
let count = 0;
for (const line of this.lines()) {
writeFileSync(
path,
`${++count > 1 ? "\r\n" : ""}${line}`,
{
encoding: "utf8",
flag: "a"
}
);
}
return this;
}
}