Ashwin Hegde
A software craftsman with a positive practicing approach towards software craftsmanship.
by Ashwin Hegde
find me at www.techjitsu.co.in
All graphical assets are licensed under the Creative Commons Attribution 3.0 Unported License.
Traditional Web Application
Blocking Sync VS Non-blocking Async
const fs = require('fs');
const data = fs.readFileSync('/file.md'); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log
Synchronous file read:
Asynchronous file read:
const fs = require('fs');
fs.readFile('/file.md', (error, data) => {
if (error) throw error; // throw error or use logger to log
console.log(data);
});
// moreWork(); will run before console.log
Warning on mixing Blocking and Non-blocking code
const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
if (err) throw err;
console.log(data);
});
fs.unlinkSync('/file.md'); // File will get delete first
Problem:
Solution: Non-blocking with correct order of execution
const fs = require('fs');
fs.readFile('/file.md', (readFileErr, data) => {
if (readFileErr) throw readFileErr;
console.log(data);
fs.unlink('/file.md', (unlinkErr) => {
if (unlinkErr) throw unlinkErr;
});
});
setImmediate():
• Executes once the current Poll phase completes
setTimeout():
• Schedule a script to be run after a minimum threshold in ms elapsed
SetTimeout Function
• The only guarantee is that the timeout will not execute sooner than the declared timeout interval.
setTimeout()
• Schedule a script to be run after a minimum threshold in ms elapsed
function myFunc(arg) {
console.log(`arg was => ${arg}`);
}
setTimeout(myFunc, 1500, 'Hello');
SetIntermediate Function
setIntermediate()
• Code will execute after any I/O operations in the current event loop
• And before any timers scheduled for the next event loop
console.log('before immediate');
setImmediate((arg) => {
console.log(`executing immediate: ${arg}`);
}, 'so immediate');
console.log('after immediate');
before immediate
after immediate
executing immediate: so immediate
Process.NextTick Function
process.nextTick()
• Will run before any Immediates that are set
• Will run before any scheduled I/O
• It non-clearable, meaning once code has been scheduled to execute, the execution cannot be stopped
SetInterval Function
setInterval()
• Infinite loop
• Same rules apply which applies for setTimeout()
function intervalFunc() {
console.log('Cant stop me now!');
}
setInterval(intervalFunc, 1500);
Cleaning the future
const timeoutObj = setTimeout(() => {
console.log('timeout beyond time');
}, 1500);
const immediateObj = setImmediate(() => {
console.log('immediately executing immediate');
});
const intervalObj = setInterval(() => {
console.log('interviewing the interval');
}, 500);
clearTimeout(timeoutObj);
clearImmediate(immediateObj);
clearInterval(intervalObj);
bounded by the performance of the process
// timeout_vs_immediate.js
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
Input
Output
$ node timeout_vs_immediate.js
timeout
immediate
$ node timeout_vs_immediate.js
immediate
timeout
Immediate callback will always executed first
// timeout_vs_immediate.js
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
});
Input
Output
$ node timeout_vs_immediate.js
immediate
timeout
$ node timeout_vs_immediate.js
immediate
timeout
const http = require('http');
http.createServer((request, response) => {
const { headers, method, url } = request;
let body = [];
request.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// BEGINNING OF NEW STUFF
response.on('error', (err) => {
console.error(err);
});
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
// Note: the 2 lines above could be replaced with this next one:
// response.writeHead(200, {'Content-Type': 'application/json'})
const responseBody = { headers, method, url, body };
response.write(JSON.stringify(responseBody));
response.end();
// Note: the 2 lines above could be replaced with this next one:
// response.end(JSON.stringify(responseBody))
// END OF NEW STUFF
});
}).listen(8080);
visit: https://nodejs.org/industry
visit: https://github.com/joyent/wiki/node-hosting
find me at www.techjitsu.co.in
By Ashwin Hegde
Quick introduction to Node.js, history, architecture, and its basics
A software craftsman with a positive practicing approach towards software craftsmanship.