-
-
Save gaurang847/f1680c593ebe56bbd2fedf15468c5b51 to your computer and use it in GitHub Desktop.
This script starts a barebones Node.js server that has three APIs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const http = require('http'); | |
const childProcess = require('child_process'); | |
const server = http.createServer((req, res) => { | |
res.setHeader('Content-Type', 'text/html'); | |
if (req.url === '/quick-api') { | |
return res.end('<h1>This API must return immediately.</h1>'); | |
} | |
if (req.url === '/slow-sync-api') { | |
childProcess.execSync('sleep 30'); | |
return res.end('<h1>This API performs a slow synchronous operation. ' | |
+ 'It will block all other requests ' | |
+ 'and bring down the performance of the entire application.</h1>'); | |
} | |
if (req.url === '/slow-async-api') { | |
return childProcess.exec('sleep 30', () => { | |
return res.end('<h1>This API also performs a slow operation. ' | |
+ 'But it does not block other requests. ' | |
+ 'The performance of rest of the application is unaffected by such slow APIs</h1>'); | |
}) | |
} | |
}) | |
server.listen(3000, () => { | |
console.log(`Server is listening`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run this script, just run
node index.js
. There are no additional packages to be installed.This script starts a barebones Node.js server that has three APIs.
GET /quick-api
GET /slow-sync-api
GET /slow-async-api
The
quick-api
API is supposed to return a response immediately.But, if you call
quick-api
afterslow-sync-api
, it does not return untilslow-sync-api
returns. This is because Node.js is single-threaded. Andslow-sync-api
calls a synchronous method that does not let the main thread do anything else till its execution is complete. It blocks all other requests.However, if you call
quick-api
afterslow-async-api
, thequick-api
works as expected. This is becauseslow-async-api
does not block the main thread till its execution is complete. The work of the asynchronous function is deferred to a worker thread and the main thread waits for the execution to complete. Meanwhile, the main thread is free to fulfill other requests.