Introduction
Node.js uses a single thread to handle many tasks at once without waiting for each to finish. This keeps programs fast and responsive.
Jump into concepts and practice - no test required
Node.js uses a single thread to handle many tasks at once without waiting for each to finish. This keeps programs fast and responsive.
import fs from 'fs'; fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data.toString()); });
import fs from 'fs'; console.log('Start'); fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log('File content:', data.toString()); }); console.log('End');
setTimeout(() => {
console.log('Timeout done');
}, 1000);
console.log('After setting timeout');This program reads a file without waiting. It prints 'Program start', then 'Program end', and finally the file content when ready.
import fs from 'fs'; console.log('Program start'); fs.readFile('example.txt', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File content:', data.toString()); }); console.log('Program end');
Non-blocking I/O lets Node.js handle many tasks smoothly.
Callbacks, promises, or async/await are ways to work with non-blocking code.
Blocking operations can slow down your app, so avoid them in Node.js.
Node.js uses a single thread but can do many things at once with non-blocking I/O.
This keeps apps fast and responsive, especially for web servers.
Use callbacks or async patterns to handle results when tasks finish.
single-threaded non-blocking I/O model?fs.readFile with a callback to handle data after reading.fs.readFile with a callback function correctly handling error and data.console.log('Start');
setTimeout(() => { console.log('Timeout done'); }, 0);
console.log('End');const fs = require('fs');
let content;
fs.readFile('data.txt', (err, data) => {
if (err) throw err;
content = data.toString();
});
console.log(content);fs.readFile runs asynchronously and needs a callback to get data.fs.readFile twice with callbacks, combine results inside the second callback only after both finish. [OK]