0
0
Node.jsframework~5 mins

Single-threaded non-blocking I/O concept in Node.js

Choose your learning style9 modes available
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.

Building a web server that handles many users at the same time
Reading or writing files without freezing the app
Making network requests while still responding to user actions
Running database queries without stopping other tasks
Syntax
Node.js
import fs from 'fs';

fs.readFile('file.txt', (err, data) => {
  if (err) throw err;
  console.log(data.toString());
});
The callback function runs after the file is read, so the program doesn't wait.
This pattern is common for non-blocking I/O in Node.js.
Examples
Shows that 'End' prints before the file content because reading is non-blocking.
Node.js
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');
Timeout runs later without stopping the program from continuing.
Node.js
setTimeout(() => {
  console.log('Timeout done');
}, 1000);
console.log('After setting timeout');
Sample Program

This program reads a file without waiting. It prints 'Program start', then 'Program end', and finally the file content when ready.

Node.js
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');
OutputSuccess
Important Notes

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.

Summary

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.