Skip to content

Commit

Permalink
Update stringifyChunked examples
Browse files Browse the repository at this point in the history
  • Loading branch information
lahmatiy committed Oct 12, 2024
1 parent 125ca12 commit c50a887
Showing 1 changed file with 28 additions and 15 deletions.
43 changes: 28 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,27 +127,40 @@ type StringifyOptions = {

Usage:

```js
import { stringifyChunked } from '@discoveryjs/json-ext';
- Getting an array of chunks:
```js
const chunks = [...stringifyChunked(data)];
```
- Iterating over chunks:
```js
for (const chunk of stringifyChunked(data)) {
console.log(chunk);
}
```
- Specifying the minimum size of a chunk with `highWaterMark` option:
```js
const data = [1, "hello world", 42];
const chunks = [...stringifyChunked(data)];
// or
for (const chunk of stringifyChunked(data)) {
console.log(chunk);
}
```
console.log([...stringifyChunked(data)]); // default 16kB
// ['[1,"hello world",42]']
Examples:
console.log([...stringifyChunked(data, { highWaterMark: 16 })]);
// ['[1,"hello world"', ',42]']
- Streaming into a file (Node.js):
console.log([...stringifyChunked(data, { highWaterMark: 1 })]);
// ['[1', ',"hello world"', ',42', ']']
```
- Streaming into a stream with a `Promise` (modern Node.js):
```js
import { pipeline } from 'node:stream/promises';
import fs from 'node:fs';
import { Readable } from 'node:stream';
Readable.from(stringifyChunked(data))
.pipe(fs.createWriteStream('path/to/file.json'));
await pipeline(
stringifyChunked(data),
fs.createWriteStream('path/to/file.json')
);
```
- Wrapping into a `Promise` for piping into a writable Node.js stream:
- Wrapping into a `Promise` streaming into a stream (legacy Node.js):
```js
import { Readable } from 'node:stream';
Expand All @@ -159,7 +172,7 @@ Examples:
.on('finish', resolve);
});
```
- Write into a file synchronously:
- Writing into a file synchronously:
> Note: Slower than `JSON.stringify()` but uses much less heap space and has no limitation on string length
```js
import fs from 'node:fs';
Expand Down

0 comments on commit c50a887

Please sign in to comment.