object_mode.js (2696B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isObject = require( '@stdlib/assert/is-plain-object' ); 24 var copy = require( '@stdlib/utils/copy' ); 25 var Stream = require( './main.js' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns a transform stream with `objectMode` set to `true`. 32 * 33 * @param {Options} [options] - stream options 34 * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk 35 * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing 36 * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` 37 * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` 38 * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends 39 * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing 40 * @throws {TypeError} options argument must be an object 41 * @throws {TypeError} must provide valid options 42 * @returns {TransformStream} transform stream 43 * 44 * @example 45 * var stdout = require( '@stdlib/streams/node/stdout' ); 46 * 47 * function stringify( chunk, enc, clbk ) { 48 * clbk( null, JSON.stringify( chunk ) ); 49 * } 50 * 51 * function newline( chunk, enc, clbk ) { 52 * clbk( null, chunk+'\n' ); 53 * } 54 * 55 * var s1 = objectMode({ 56 * 'transform': stringify 57 * }); 58 * 59 * var s2 = objectMode({ 60 * 'transform': newline 61 * }); 62 * 63 * s1.pipe( s2 ).pipe( stdout ); 64 * 65 * s1.write( {'value': 'a'} ); 66 * s1.write( {'value': 'b'} ); 67 * s1.write( {'value': 'c'} ); 68 * 69 * s1.end(); 70 * 71 * // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n' 72 */ 73 function objectMode( options ) { 74 var opts; 75 if ( arguments.length ) { 76 if ( !isObject( options ) ) { 77 throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); 78 } 79 opts = copy( options ); 80 } else { 81 opts = {}; 82 } 83 opts.objectMode = true; 84 return new Stream( opts ); 85 } 86 87 88 // EXPORTS // 89 90 module.exports = objectMode;