Appearance
fs Module
The built-in fs
module in Node.js handles file system operations, allowing you to read and write files. Unlike other JavaScript modules, fs
provides both asynchronous and synchronous methods.
Asynchronous File Reading
Asynchronous methods allow JavaScript to continue executing without waiting for I/O operations. For example, to read a text file asynchronously:
javascript
// read-text-file-async.mjs
import { readFile } from 'node:fs';
console.log('BEGIN');
readFile('sample.txt', 'utf-8', function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
console.log('END');
Here, the readFile
function's callback receives two parameters: err
and data
. If successful, err
is null
and data
contains the file content. The output shows "END" printed before the file content because of asynchronous execution.
For binary files, you can read them like this:
javascript
import { readFile } from 'node:fs';
readFile('sample.png', function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data instanceof Buffer); // true
console.log(data); // Buffer object
}
});
Synchronous File Reading
If you prefer synchronous reading, use the readFileSync
method:
javascript
// read-text-file-sync.mjs
import { readFileSync } from 'node:fs';
console.log('BEGIN');
try {
let s = readFileSync('sample.txt', 'utf-8');
console.log(s);
} catch (err) {
console.log(err);
}
console.log('END');
In this case, the function directly returns the file content, and you must handle errors using try...catch
.
Writing Files
To write data to a file, use writeFile
:
javascript
// write-file-async.mjs
import { writeFile } from 'node:fs';
let data = 'Hello, Node.js';
writeFile('output.txt', data, function (err) {
if (err) {
console.log(err);
}
});
The parameters are the file name, data, and a callback function.
Getting File Stats
To retrieve information about a file, use stat
:
javascript
import { stat } from 'node:fs';
stat('sample.png', function (err, st) {
if (err) {
console.log(err);
} else {
console.log('isFile: ' + st.isFile());
console.log('size: ' + st.size);
}
});
You can also use statSync()
for synchronous file stats.
Using Promises
Node.js provides a promise-based version of fs
:
javascript
// async-read.mjs
import { readFile } from 'node:fs/promises';
async function readTextFile(path) {
return await readFile(path, 'utf-8');
}
readTextFile('sample.txt').then(s => console.log(s));
Asynchronous vs. Synchronous
While synchronous methods are simpler, they can block the server from responding if used extensively in server code. Use synchronous operations only during startup or shutdown, while asynchronous methods are ideal for regular operations. For many async functions, the promise-based fs/promises
is often more convenient.