* Create a transform stream that prefixes each line with a tag. * @param {Object} opts * @param {string} [opts.tag]
(opts = {})
| 11 | * @param {string} [opts.tag] |
| 12 | */ |
| 13 | function createLogPrefixer(opts = {}) { |
| 14 | const tag = opts.tag || ''; |
| 15 | let leftover = ''; |
| 16 | return new Transform({ |
| 17 | transform(chunk, encoding, callback) { |
| 18 | const data = leftover + chunk.toString(); |
| 19 | const lines = data.split(/\r?\n/); |
| 20 | leftover = lines.pop(); |
| 21 | for (const line of lines) { |
| 22 | this.push(tag ? `${tag} ${line}\n` : `${line}\n`); |
| 23 | } |
| 24 | callback(); |
| 25 | }, |
| 26 | flush(callback) { |
| 27 | if (leftover) { |
| 28 | this.push(tag ? `${tag} ${leftover}\n` : `${leftover}\n`); |
| 29 | } |
| 30 | callback(); |
| 31 | } |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Execute a command asynchronously, piping stdio by default. |