NodeCEC.prototype.start = function() { this.client = spawn('cec-client'); this.stdout = byline(this.client.stdout); this.stderr = byline(this.client.stderr); this.stdin = this.client.stdin; var that = this; this.stdout.on('data', function(data) { that.handleData(data); }); this.stderr.on('data', function(data) { that.handleError(data); }); this.client.on('close', function(code) { that.emit('close', code); that.ready = false; that.client = null; }); this.client.on('error', function(err) { that.handleError(err); }); }
// Setup client function( next ) { // Attach client ID socket.id = uuid.v4(); if( self.config.compression !== 'none' ) { // Create decompressor switch( self.config.compression ) { default: case 'gzip': decompressor = zlib.createGunzip(); break; } self.parser = byline( socket.pipe( decompressor ), { end: false }); } else { self.parser = byline( socket, { end: false }); } // Notify client closed socket.on( 'close', function() { self.emit( 'client:close', this ); }); // Notify client connection self.emit( 'client:open', socket ); next( null ); },
Compiler.prototype.runTsc = function (callback) { var _this = this; var proc = tsc.exec(['@' + this.tscArgumentsFile], this.tscOptions); var stdout = byline(proc.stdout); var stderr = byline(proc.stderr); proc.on('exit', function (code) { if (code !== 0) { callback(new Error('tsc command has exited with code:' + code)); } else { callback(null); } }) proc.on('error', function (err) { _this.emit('error', err); }); stdout.on('data', function (chunk) { _this.emit('stdout', chunk); }); stderr.on('data', function (chunk) { _this.emit('stderr', chunk); }); return proc; };
Shell.prototype._exec = function(command, options) { options = options || {}; var self = this; options = extend(extend({}, self._options), options); // clone and extend var result = { code: 0, stdout: null, stderr: null }; self._logger.command(command); var fiber = Fiber.current; var proc = exec(command, { maxBuffer: 1000*1024 }); proc.stdout.on('data', function(data) { result.stdout = (result.stdout || '') + data; }); proc.stderr.on('data', function(data) { result.stderr = (result.stderr || '') + data; }); byline(proc.stdout).on('data', function(data) { if(!options.silent) { self._logger.stdout(String(data).trim()); } }); byline(proc.stderr).on('data', function(data) { if(options.failsafe) { self._logger.stdwarn(String(data)); } else { self._logger.stderr(String(data)); } }); proc.on('close', function(code) { result.code = code; if(result.code === 0) { self._logger.success('ok'); } else { if(options.failsafe) { self._logger.warn('failed safely (' + result.code + ')'); } else { self._logger.error('failed (' + result.code + ')'); throw new errors.CommandExitedAbormallyError( 'Command exited abnormally on ' + self._context.remote.host); } } fiber.run(result); }); return Fiber.yield(); };
function Consolidator (asynchronous, synchronous, queue) { this._exited = false this._series = 1 this._readable = { asynchronous: new Staccato.Readable(byline(asynchronous)), synchronous: new Staccato.Readable(byline(synchronous)) } this._queue = queue }
HDMICEC.prototype.start = function() { var self = this; // Save the current object instance for use by the callbacks if (MODE === 'NOCECDEVICE') { // Run in Dev/Test model without libcec/cec-client installed // Run the tests var tests = require('./tests.json'); this.testsTimer = setInterval(function(){ console.log('\n----------- Running tests -------------'); for (var testname in tests) { if (testname.charAt(0) != '_') { self.handleData(tests[testname].traffic); } } // Tests are repeated every 30 seconds },30000); } else { // run cec-client in a subprocess, displaying only TRAFFIC information (log level = 8) this.cec_client = spawn('cec-client', ['-d', '8', settings.adapterport]); // trap stdout and stderr from the spawned application this.stdout = byline(this.cec_client.stdout); this.stderr = byline(this.cec_client.stderr); // Redirect stdin to the running cec-client this.stdin = this.cec_client.stdin; // Save the current object instance for use by the callbacks //var self = this; this.stdout.on('data', function(data) { // Data received from cec-client self.handleData(data); }); this.stderr.on('data', function(data) { // Error received from cec-client self.handleError(data); }); this.cec_client.on('error', function(err) { // Other error from cec-client self.handleError(err); }); this.cec_client.on('close', function(code) { // The spawned cec-client has closed self.emit('close', code); self.ready = false; self.cec_client = null; }); } };
req.on('response', function(res){ // stream byline(res) .on('error', done) .on('finish', cb) .on('data', count); // size stats.size += parseInt(res.headers['content-length']); // count function count(line){ line = line.toString().trim(); if (comment(line)) return; ++stats.sloc; } // comment var within; function comment(line){ if (/^\*\//.test(line)) { within = false; return /^\*\/$/.test(line); } return within || (within = /^\/\*/.test(line)) || /^\/\*.*\*\/$/.test(line) || /^\/\//.test(line); } }).end();
return Bacon.fromBinder(sink => { let ls = byline(src, {encoding: 'utf8'}); ls.on('data', chunk => { sink(new Bacon.Next(tokenizeLine(chunk))) }); ls.on('end', () => { sink(new Bacon.End()) }); return () => {} });
return new Promise(function(resolve) { var countries = []; var stream = byline(fs.createReadStream('input/countryInfo.txt', {encoding: 'utf8'})); stream.on('data', function(line) { if (_.startsWith(line, '#')) return; var data = line.split('\t'); countries.push({ iso: data[0], iso3: data[1], //iso_numeric: data[2], //fips: data[3], name: data[4], //capital: data[5], //area: data[6], //population: data[7], //continent: data[8], //tld: data[9], //currency_code: data[10], //currency_name: data[11], //phone: data[12], //postal_code_format: data[13], //postal_code_regex: data[14], //languages: data[15], //geoname_id: data[16], //neighbours: data[17], cities: [] }); }).on('end', function() { resolve(countries); }); });
Parser.toArray = function (dxfPath, callback) { var stream = byline(fs.createReadStream(dxfPath, { encoding: 'utf8' })), sectionNameTab = ['HEADER', 'CLASSES', 'TABLES', 'BLOCKS', 'ENTITIES', 'OBJECTS', 'THUMBNAILIMAGE'], sectionCur = '', dxfTab = [], section = false, endsec = false; stream.on('data', function (line) { if (sectionNameTab.indexOf(line) != -1) { sectionCur = line.toLowerCase(); section = true; dxfTab[sectionCur] = []; endsec = false; } else if (section === true) { if (line === 'ENDSEC') { endsec = true; section = false; sectionCur = ''; } else if (endsec === false) { dxfTab[sectionCur].push(line); } } }); stream.on('end', function () { callback(dxfTab); }); };
setTimeout(function(){ var fs = require('fs'), byline = require('byline'); var stream = byline(fs.createReadStream(filepath, { encoding: 'utf8' })); var found = false; stream.on('data', function(line) { if (found) return; var record = JSON.parse(line); if (record._id == path){ found = true; stream.end(); return callback(null, record); } }); stream.on('end', function(){ if (!found) callback(null, null); }); }, 2000)
Conf.prototype._read = function (callback) { var self = this; if (!this.values) this._init(); if (!this._conf) throw new Error('Config file must be defined.'); var stream = byline(fs.createReadStream(this._conf, { encoding: 'utf8' })); stream.on('data', function (line) { if (line.indexOf('#') === 0) { return; } if (line.match(/\".*\"/g)) { line = line.replace(line.match(/\".*\"/g)[0], line.match(/\".*\"/g)[0].replace(/ +/g, '_')); } line = line.replace(/^\B +/, '').split(/ +/g); for (var i = 0, l = self.values.length; i < l; i++) { self.values[i].push(line[i] ? line[i].replace(/_/g, ' ').replace(/\"/g, '') : line[i]); } }); stream.on('end', function () { callback(null); }); stream.on('error', function (error) { callback(error); }); };
function Session(server, socket) { var self = this; this._socket = socket; this._userLocked = false; this._authed = false; this._server = server; this._rooms = []; this._usernames = []; this.id = null; this.currentRoom = null; byline(socket).on('data', this.parseMessage.bind(this)); socket.on('close', function() { // let's remove the userId from the online list delete self._server._userList[self.id]; if ( self.currentRoom ) { self.currentRoom.emit('user_disconnected', { userId:self.id }); } self._rooms.forEach(function(room) { room.removeSession(self); }); }); };
TickBro.prototype.processLogFile = function (callback) { var me = this; var totalSize = fs.statSync('v8.log').size; var doneSize = 0; var lastProgress = 0; var stream = byline(fs.createReadStream('v8.log', {flags:'r'})); stream.on('data', function (line) { line = line.toString('utf-8'); stream.pause(); setImmediate(function () { Fiber(function() { doneSize += line.length + 1; var currentTime = new Date().getTime(); if ((currentTime - lastProgress) > 500) { me.emit('progress', { doneBytes: doneSize, totalBytes: totalSize, percent: Math.round(doneSize / totalSize * 1000) / 10 }); lastProgress = currentTime; } me.tickProcessor.processLogLine(line); stream.resume(); }).run(); }); }); // TODO: The end event might complete before the last line is processed. stream.on('end', callback || function () {}); };
function Session(server, socket) { var self = this; this._socket = socket; this._authed = false; this._server = server; this._rooms = []; this.id = null; this.currentRoom = null; byline(socket).on('data', this.parseMessage.bind(this)); socket.on('close', function() { if(self.currentRoom) { self.currentRoom.emit('user_disconnected', {userId:self.id}); } self._rooms.forEach(function(room){ room.removeSession(self); }); }); }
it('should start a build and report results', function(done) { sandbox.stub(builder, 'findBuild').yields(); sandbox.stub(builder, 'startBuild').yields(null, 'fake'); sandbox.stub(builder, 'monitor', function() { let emitter = new events.EventEmitter(); process.nextTick(emitter.emit.bind(emitter, 'start')); process.nextTick(emitter.emit.bind(emitter, 'progress', { message: 'Forward, not backward!' })); process.nextTick(emitter.emit.bind(emitter, 'done', { result: { compile: true, public: false, hidden: true } })); return emitter; }); let expected = [ /started/i, /Forward/, /compilation succeeded/i, /public tests failed/i, /details.*labs\/lab2\/alice/i ]; let req = request.post(root + 'build/labs/lab2/alice/abcd123'); byline(req, { encoding: 'utf8' }).on('data', function(line) { line.should.match(expected.shift()); if (expected.length == 0) { done(); } }); });
function Searcher() { var self = this; this.state = {}; this.state.readLine = this._wait_ready; this.state.queue = []; this.state.current = undefined; this.state.ready = false; this.child = child_process.spawn("./search_server", [], { }); this.child.stdout.setEncoding('utf8'); byline(this.child.stdout).on('data', function(line) { console.log(line); self.state.readLine.call(self, line); }); this.child.stderr.setEncoding('utf8'); this.child.stderr.on('data', function(data) { console.error(data); }); this.child.stdin.setEncoding('utf8'); this.child.unref(); }
return (function () { var platformData = _this.$platformsData.getPlatformData(_this.platform); if (_this.$options.rebuild) { _this.$platformService.prepareAndBuild(_this.platform).wait(); } var emulatorPackage = _this.$platformService.getLatestApplicationPackageForEmulator(platformData).wait(); var args = shouldBreak ? "--nativescript-debug-brk" : "--nativescript-debug-start"; var child_process = _this.$iOSEmulatorServices.runApplicationOnEmulator(emulatorPackage.packageName, { waitForDebugger: true, captureStdin: true, args: args, appId: _this.$projectData.projectId, skipInstall: _this.$config.debugLivesync }).wait(); var lineStream = byline(child_process.stdout); _this._childProcess = child_process; lineStream.on('data', function (line) { var lineText = line.toString(); if (lineText && _.startsWith(lineText, _this.$projectData.projectId)) { var pid = _.trimStart(lineText, _this.$projectData.projectId + ": "); _this._lldbProcess = _this.$childProcess.spawn("lldb", ["-p", pid]); _this._lldbProcess.stdin.write("process continue\n"); } else { process.stdout.write(line + "\n"); } }); _this.wireDebuggerClient().wait(); }).future()();
extractHeaders: function () { var lineStream = byline(inStream) var tmpOut = fs.createWriteStream(tempFile) lineStream.on('data', function (data) { lineCount += 1 try { var obj = JSON.parse(data) keys = util.merge(keys, obj) tmpOut.write(data + '\n') } catch (err) { console.error('Parsing error on line (%d): %s', lineCount, err) } }) lineStream.on('end', function () { if (opts.blacklist) { opts.blacklist.forEach(function (key) { if (keys[key]) delete keys[key] }) } keys = Object.keys(keys) // convert object to array tmpOut.end(function () { setTimeout(function () { flow.next() }, 25) // breath }) }) lineStream.resume() },
return new Promise(function(resolve) { var cities = []; var stream = byline(fs.createReadStream('input/cities15000.txt', {encoding: 'utf8'})); stream.on('data', function(line) { var data = line.split('\t'); var city = { //geoname_id: data[0], name: data[1], asciiname: data[2], //alternatenames: data[3], latitude: data[4], longitude: data[5], //feature_class: data[6], //feature_code: data[7], //cc2: data[9], //admin1_code: data[10], //admin2_code: data[11], //admin3_code: data[12], //admin4_code: data[13], //population: data[14], //elevation: data[15], //dem: data[16], //timezone: data[17], //modified_date: data[18], country_code: data[8], //required for country matching, omitted from output }; cities.push(city); }).on('end', function() { resolve(cities); }); });
function autoComplete(opts, cb) { var stream; if (!cb) { cb = opts; opts = {}; } var dictionary = opts.dictionary || DEFAULT_DICTIONARY; try { debug('Starting to read dictionary'); stream = byline(fs.createReadStream(dictionary, { encoding: 'utf8' })); } catch (err) { return cb(err); } var trie = new Trie(); debug('Starting to add words in trie'); stream.on('data', function(line) { trie.add(line); }); stream.on('end', function(line) { debug('Dictionary read completed'); cb(null, trie); }); }
// Exported function function lstToJSON ( options ) { options = options || {}; if ( options.inputFile && typeof options.inputFile === 'string' ) { INPUT_FILE = options.inputFile; } if ( options.outputFile && typeof options.outputFile === 'string' ) { OUTPUT_FILE = options.outputFile; } headers = options.headers; if ( !headers || !headers.length ) { console.error( 'WARNING: no headers provided, cannot parse lst file.' ); } // Process files var inputStream = byline(fs.createReadStream(INPUT_FILE, { encoding: 'utf8' })); var transformStream = transform( transformLstLine ); var outputStream = fs.createWriteStream( OUTPUT_FILE ); transformStream.on('error', function handleStreamError( err ) { console.error('Stream transform error @ ' + INPUT_FILE + ' line ' + lineNumber + ': ', err ); // Don't pass on input if there's an error // If we stop it here, the file will never get written. transformStream.unpipe(); transformStream.end(); }); inputStream.pipe(transformStream).pipe( outputStream ); }
http.get(bgpTableUrl, (response) => { response.pipe(bz2.stdin); let prev = null; const writeStream = fs.createWriteStream(dst); bz2.stdout.pipe(byline()) .on("data", (line) => { let tokens = line .toString() .trim() .replace(/\t+/g, " ") .replace(/"/g, "") .split(" "); let len = tokens.length; let asn = tokens[len-3].trim(); let network = tokens[len-2].trim(); let netmask = tokens[len-1].trim(); let formatted = `${network}/${netmask} ${asn}\n`; if(formatted != prev) { writeStream.write(formatted); prev = formatted; } }) .on("end", () => { writeStream.close(); callback('finished'); }); });
exports.parse = function(src) { if (!src.pipe) throw new Error('first argument must be Readable'); var gl = Gitlog(); gl.on('finish', function() { gl.emit('commit', gl._current); }); return byline(src).pipe(gl); }
preferLocalBin(name, function (preferredName) { child = child_process.spawn(preferredName, args); task.processes.push(child); debug('Added %d to the processes of %s', child.pid, task.key); byline(child.stdout).pipe(task.stdout); byline(child.stderr).pipe(task.stderr); child.on('error', function (error) { console.error(style(' {red}Error:{reset} Failed to run %s: %s'), cmd, error.toString()); }); child.on('close', function () { done(); }); });
module.exports.getErrorsJson = function(req, res, next) { var stream = byline(fs.createReadStream(env.config.server.logfile, { encoding: 'utf8' })); var errorList = []; stream.on('data', function(line) { errorList.push(line + '-' + env.hostname); }); stream.on('end', function() { res.send(errorList.reverse()); }); }
function parseBuffer(buf, callback) { var byline = require('byline'), streamBuffers = require("stream-buffers"), output = new streamBuffers.ReadableStreamBuffer(); output.pause(); output.put(buf); var stream = byline(output); output.resume(); parse(stream, output, callback); }
}, (err, stream) => { if (ERR(err, callback)) return; const out = byline(stream); out.on('data', (line) => { const newline = `container> ${line.toString('utf8')}`; logger.info(newline); output += (newline + '\n'); }); callback(null, container); });
q.async(function*() { const baseUrl = options.baseUrl; for(let i = 0; i < options.concurrency; ++i) { const requestStream = byline(fs.createReadStream(options.requestsFile, {encoding: 'utf8'})); const reader = new Reader(); requestStream.pipe(reader); fetchLoop(baseUrl, reader); yield q.delay(10000); } })().done();
self._connection.exec(command, options.exec || {}, function(err, stream) { stream.on('data', function(data) { result.stdout = (result.stdout || '') + data; }); stream.stderr.on('data', function(data) { result.stderr = (result.stderr || '') + data; }); byline(stream).on('data', function(data) { if(!options.silent) { self._logger.stdout(data); } }); byline(stream.stderr).on('data', function(data) { if(options.failsafe) { self._logger.stdwarn(data); } else { self._logger.stderr(data); } }); stream.on('exit', function(code) { result.code = code; }); stream.on('close', function() { if(result.code === 0) { self._logger.success('ok'); } else if(options.failsafe) { self._logger.warn('safely failed (' + result.code + ')'); } else { self._logger.error('failed (' + result.code + ')'); throw new errors.CommandExitedAbormallyError( 'Command exited abnormally on ' + self._context.remote.host); } fiber.run(result); }); });