Complete the code to read a file asynchronously using Node.js built-in module.
import { readFile } from 'fs/promises'; async function readData() { const data = await readFile('[1]', 'utf8'); console.log(data); } readData();
The path './data.txt' correctly points to the file in the current directory. Using await with readFile reads the file asynchronously.
Complete the code to handle an asynchronous operation with a callback in Node.js.
import { readFile } from 'fs'; readFile('[1]', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });
The path './file.txt' correctly points to the file in the current directory. The callback handles the asynchronous read operation.
Fix the error in the async function to properly catch errors using try-catch.
import { readFile } from 'fs/promises'; async function loadFile() { [1] { const content = await readFile('./info.txt', 'utf8'); console.log(content); } catch (error) { console.error('Error:', error); } } loadFile();
The try block is needed to wrap the await call so errors can be caught in the catch block.
Fill both blanks to create a Promise that resolves after a delay and use async/await to wait for it.
function delay(ms) {
return new Promise(([1], reject) => {
setTimeout(() => [2](), ms);
});
}
async function run() {
console.log('Start');
await delay(1000);
console.log('End after 1 second');
}
run();The Promise constructor receives resolve and reject functions. Calling resolve() inside setTimeout signals the Promise is done.
Fill all three blanks to create an async function that fetches JSON data and handles errors.
import fetch from 'node-fetch'; async function getData(url) { try { const response = await fetch([1]); if (!response.ok) throw new Error('Network error'); const data = await response.[2](); return [3]; } catch (err) { console.error('Fetch failed:', err); } }
The fetch function takes the URL. The response.json() method parses JSON data. Returning data gives the caller the fetched content.