UNPKG

1.37 kBJavaScriptView Raw
1// Copyright © 2017 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16// stolen from http://strongloop.com/strongblog/practical-examples-of-the-new-node-js-streams-api/
17const stream = require('stream');
18
19module.exports = function() {
20 const liner = new stream.Transform({ objectMode: true });
21
22 liner._transform = function(chunk, encoding, done) {
23 let data = chunk.toString();
24 if (this._lastLineData) {
25 data = this._lastLineData + data;
26 }
27
28 const lines = data.split('\n');
29 this._lastLineData = lines.splice(lines.length - 1, 1)[0];
30
31 for (const i in lines) {
32 this.push(lines[i]);
33 }
34 done();
35 };
36
37 liner._flush = function(done) {
38 if (this._lastLineData) {
39 this.push(this._lastLineData);
40 }
41 this._lastLineData = null;
42 done();
43 };
44
45 return liner;
46};