Node.js Callback Functions
Node.js is a JavaScript runtime based on the Chrome V8 engine, which allows JavaScript to run on the server side, outside the browser.
One of the core features of Node.js is its non-blocking I/O (input/output) model, which makes Node.js very suitable for handling high-concurrency network applications.
The direct manifestation of asynchronous programming in Node.js is callbacks.

In Node.js, a callback function is an asynchronous programming pattern used to handle I/O operations such as file reads and writes, database interactions, and network requests. These operations usually take a relatively long time; if a synchronous approach were used, it would block the entire program's execution until the operation completes.
Using callback functions, Node.js can continue executing other code while I/O operations are in progress, and execute the callback function once the I/O operation completes.
Node.js is single-threaded, but achieves asynchronous operations through event-driven and callback mechanisms.
Use Cases
- I/O operations such as reading and writing files.
- Handle network requests.
- Database queries.
For example, we can read a file while executing other commands; once the file read is complete, we return the file content as an argument to the callback function. In this way, there is no blocking or waiting for file I/O operations while executing code. This greatly improves the performance of Node.js, allowing it to handle a large number of concurrent requests.
A callback function generally appears as the last argument of a function:
function foo1(name, age, callback) { }
function foo2(value, callback1, callback2) { }
Example
Blocking code example
Create a file named input.txt with the following content:
Runoob Tutorial官网地址:www.runoob.com
Create a file named main.js with the following code:
Example
var
fs
=
require
(
"fs"
)
;
var
data
=
fs.
readFileSync
(
'input.txt'
)
;
console.
log
(
data.
toString
(
)
)
;
console.
log
(
"Program execution finished!"
)
;
The result of executing the above code is as follows:
$ node main.js
Runoob Tutorial官网地址:www.runoob.com
程序执行结束!
Non-blocking code example
Create a file named input.txt with the following content:
Runoob Tutorial官网地址:www.runoob.com
Create a file named main.js with the following code:
Example
var
fs
=
require
(
"fs"
)
;
fs.
readFile
(
'input.txt'
,
function
(
err
,
data
)
{
if
(
err
)
return
console.
error
(
err
)
;
console.
log
(
data.
toString
(
)
)
;
}
)
;
console.
log
(
"Program execution finished!"
)
;
Parameter Explanations:
erris the error object; it has a value if the read fails.datais the content read from the file.
The result of executing the above code is as follows:
$ node main.js
程序执行结束!
Runoob Tutorial官网地址:www.runoob.com
From the above two examples, we understand the difference between blocking and non-blocking calls:
-
In the first example, the program executes only after the file has been read.
-
In the second example, we do not need to wait for the file read to complete, so we can execute the following code while the file is being read, greatly improving program performance.
Therefore, blocking executes in sequence, while non-blocking does not need to follow a sequence, so if you need to handle the arguments of a callback function, you need to write them inside the callback function.
Callback Hell
When multiple asynchronous operations need to be executed in sequence, callback functions lead to code nesting, making the code difficult to read and maintain.
Example
fs.
readFile
(
'file1.txt'
,
'utf8'
,
(
err
,
data1
)
=>
{
if
(
err
)
{
console.
error
(
'Error reading file1:'
,
err
)
;
return
;
}
fs.
readFile
(
'file2.txt'
,
'utf8'
,
(
err
,
data2
)
=>
{
if
(
err
)
{
console.
error
(
'Error reading file2:'
,
err
)
;
return
;
}
fs.
readFile
(
'file3.txt'
,
'utf8'
,
(
err
,
data3
)
=>
{
if
(
err
)
{
console.
error
(
'Error reading file3:'
,
err
)
;
return
;
}
console.
log
(
'Data from all files:'
,
data1
,
data2
,
data3
)
;
}
)
;
}
)
;
}
)
;
To improve code readability and maintainability, you can use the following approaches:
- Promises: Promises are a new asynchronous programming pattern that allows you to handle asynchronous operations in a chained manner, avoiding callback hell.
- async/await: based on Promises,
async/awaitprovides an asynchronous programming style closer to synchronous code, making asynchronous code easier to understand and maintain. - Event-driven programming: Node.js also supports event-driven programming, handling asynchronous operations by listening for and triggering events.
1. Using async/await
async/await is syntactic sugar introduced in ES2017 that lets you handle asynchronous operations more conveniently and avoid callback hell.
Example
const
fs
=
require
(
'fs'
)
.
promises
;
async
function
readFiles
(
)
{
try
{
const
data1
=
await fs.
readFile
(
'file1.txt'
,
'utf8'
)
;
const
data2
=
await fs.
readFile
(
'file2.txt'
,
'utf8'
)
;
const
data3
=
await fs.
readFile
(
'file3.txt'
,
'utf8'
)
;
console.
log
(
'Data from all files:'
,
data1
,
data2
,
data3
)
;
}
catch
(
err
)
{
console.
error
(
'Error reading files:'
,
err
)
;
}
}
readFiles
(
)
;
2. Using Promises
Promises are another way to handle asynchronous operations, allowing you to chain the then method to avoid nested callbacks.
Example
const
fs
=
require
(
'fs'
)
.
promises
;
fs.
readFile
(
'file1.txt'
,
'utf8'
)
.
then
(
data1
=>
{
console.
log
(
'Data from file1:'
,
data1
)
;
return
fs.
readFile
(
'file2.txt'
,
'utf8'
)
;
}
)
.
then
(
data2
=>
{
console.
log
(
'Data from file2:'
,
data2
)
;
return
fs.
readFile
(
'file3.txt'
,
'utf8'
)
;
}
)
.
then
(
data3
=>
{
console.
log
(
'Data from file3:'
,
data3
)
;
}
)
.
catch
(
err
=>
{
console.
error
(
'Error reading files:'
,
err
)
;
}
)
;
Callback functions are a fundamental way to handle asynchronous operations in Node.js, but as application complexity increases, the problem of callback hell becomes more pronounced. By using async/await or Promises, you can significantly improve code readability and maintainability.