Skip to content

Instantly share code, notes, and snippets.

View chaiwa-berian's full-sized avatar

Berian chaiwa-berian

View GitHub Profile
@chaiwa-berian
chaiwa-berian / push_chunk_to_nodejs_stream_on_demand.js
Last active August 20, 2018 18:07
Push chunk to nodejs stream on demand
//we could avoid buffering data altogether and only generate the data when the consumer asks for it.
//We can push chunks on-demand by defining a ._read function
//To show that our _read function is only being called when the consumer requests,
//we can modify our readable stream code slightly to add a delay:
var Readable = require('stream').Readable;
var rs = Readable();
var c = 97 - 1;
var Readable = require('stream').Readable;
var rs = new Readable;
rs.push('beep');
rs.push('boop\n');
rs.push(null); //Tells the consumer that rs is done outputting data
rs.pipe(process.stdout);
const http = require('http');
const fs = require('fs');
var server = http.createServer((req, res)=>{
var stream = fs.createReadStream(__dirname + '/data.txt');
stream.pipe(res);
});
server.listen(3000);
const http = require('http');
const fs = require('fs');
var server = http.createServer((req,res)=>{
fs.readFile(__dirname + '/data.txt', function(err, data){
if(err){
res.end(err);
}
res.end(data);
}
var obj ={
prop: (() => { return ( 3 > 4 ? 'yes' : 'no' );})();
}
console.log(obj.prop); //output: no
//We are triggering start but we are catching done
var Job = require('./nodejs_inherit_events_main_job'); //inherit from main Job
var job = new Job();
job.on('done', function(details){ //Subscribe to the main job's done event
console.log('Job was completed at', details.completedOn);
job.removeAllListeners();
});
job.emit('start'); //Fire-up the main job
//We emit done and catch start events
var util = require('util');
var Job = function Job(){
//we will use it later to pass this to a closure
var job = this;
job.process = function(){
//emulate the delay of a job async
setTimeout(function(){
@chaiwa-berian
chaiwa-berian / nodejs_events_demo.js
Last active August 13, 2018 18:28
Nodejs Events Demo
var events = require('events');
var emitter = new events.EventEmitter();
emitter.once('knock', function(){ //subscribe to the event
console.log('Who\'s there???');
});
emitter.on('knock', function(){ //subscribe to the event
console.log('Leave us in peace, please!!!');
});
@chaiwa-berian
chaiwa-berian / i_o_blocking_code_sample.js
Last active August 13, 2018 17:11
Nodejs Blocking Code Example
console.log('Step: 1');
var startTime = Date.now();
console.log('Start time: ', startTime);
for(let i=1;i<10000000000;i++){
//Do Nothing
}
var endTime = Date.now();
console.log('Step: 2 started!');
console.log('End Time: ', endTime);
@chaiwa-berian
chaiwa-berian / one_line_of_code_server
Created August 2, 2018 18:28
Nodejs Server in one line of code
require('http').createServer((req,res)=>res.end("Hey!")).listen(3000,'127.0.0.1');