Complete the code to read a file asynchronously using Node.js.
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); console.log('Reading file...'); // This is non-blocking because [1]
The readFile function runs asynchronously, so the program does not wait for it to finish before moving on. This is why the console logs 'Reading file...' first.
Complete the code to create a simple HTTP server that handles requests without blocking.
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }); server.listen(3000); console.log('Server running at http://localhost:3000/'); // This server is non-blocking because it uses [1]
The server uses asynchronous callbacks to handle requests, so it does not block the main thread while waiting for requests.
Fix the error in the code to correctly use non-blocking I/O for reading a file.
const fs = require('fs'); const data = fs.readFileSync('data.txt', 'utf8'); console.log(data); console.log('File read complete'); // To make this non-blocking, replace readFileSync with [1]
readFileSync blocks the thread until the file is read. Using readFile makes the operation asynchronous and non-blocking.
Fill both blanks to create a non-blocking timer that logs a message after 2 seconds.
console.log('Start'); setTimeout(() => { console.log([1]); }, [2]); console.log('End');
The setTimeout function schedules the callback to run after 2000 milliseconds (2 seconds) without blocking the main thread.
Fill all three blanks to create a Promise that resolves after 1 second and logs the result.
const wait = new Promise((resolve, reject) => {
setTimeout(() => {
resolve([1]);
}, [2]);
});
wait.then((message) => {
console.log([3]);
});The Promise resolves with the message 'Success' after 1000 milliseconds. The then method receives the message and logs it.