Skip to content

Commit 75a620f

Browse files
committed
feat: make ProcessOutput iterable
closes #1053 closes #1027 relates #1088 relates #984
1 parent ea5f5c0 commit 75a620f

File tree

4 files changed

+32
-3
lines changed

4 files changed

+32
-3
lines changed

.size-limit.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
{
33
"name": "zx/core",
44
"path": ["build/core.cjs", "build/util.cjs", "build/vendor-core.cjs"],
5-
"limit": "77 kB",
5+
"limit": "77.5 kB",
66
"brotli": false,
77
"gzip": false
88
},
@@ -30,7 +30,7 @@
3030
{
3131
"name": "all",
3232
"path": "build/*",
33-
"limit": "849 kB",
33+
"limit": "850 kB",
3434
"brotli": false,
3535
"gzip": false
3636
}

src/core.ts

+14-1
Original file line numberDiff line numberDiff line change
@@ -758,13 +758,26 @@ export class ProcessOutput extends Error {
758758
}
759759

760760
lines(): string[] {
761-
return this.valueOf().split(/\r?\n/)
761+
return [...this]
762762
}
763763

764764
valueOf(): string {
765765
return this.stdall.trim()
766766
}
767767

768+
*[Symbol.iterator](): Iterator<string> {
769+
let buffer = ''
770+
771+
for (const chunk of this._dto.store.stdall) {
772+
buffer += chunk.toString()
773+
const lines = buffer.split(/\r?\n/)
774+
buffer = lines.pop() ?? ''
775+
yield* lines
776+
}
777+
778+
if (buffer) yield buffer
779+
}
780+
768781
static getExitMessage = formatExitMessage
769782

770783
static getErrorMessage = formatErrorMessage;

test/core.test.js

+15
Original file line numberDiff line numberDiff line change
@@ -1162,6 +1162,21 @@ describe('core', () => {
11621162
globalThis.Blob = Blob
11631163
})
11641164

1165+
test('[Symbol.Iterator]', () => {
1166+
const o = new ProcessOutput({
1167+
store: {
1168+
stdall: ['foo\nba', 'r\nbaz'],
1169+
},
1170+
})
1171+
const lines = []
1172+
const expected = ['foo', 'bar', 'baz']
1173+
for (const line of o) {
1174+
lines.push(line)
1175+
}
1176+
assert.deepEqual(lines, expected)
1177+
assert.deepEqual(o.lines(), expected)
1178+
})
1179+
11651180
describe('static', () => {
11661181
test('getExitMessage()', () => {
11671182
assert.match(

test/smoke/node.test.mjs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import 'zx/globals'
1919
{
2020
const p = await $`echo foo`
2121
assert.match(p.stdout, /foo/)
22+
assert.deepEqual(p.lines(), ['foo'])
2223
}
2324

2425
// captures err stack

0 commit comments

Comments
 (0)