File operations are essential when working with data in Node.js. The built-in fs module in Node.js provides functionalities to perform various file operations, such as reading from or writing to files, handling different file formats, and managing directories.
When it comes to reading files in different formats, Node.js offers methods to handle text files, JSON files, CSV files, and binary files effectively.
For reading text files, you can use the fs.readFile() method with the ‘utf8’ encoding. An example of reading a text file named ‘example.txt’ is provided:
“`javascript
const fs = require(‘fs’);
fs.readFile(‘example.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(‘Text file content:’, data);
});
“`
For reading JSON files, you can use the fs.readFile() method and then parse the data using JSON.parse(). An example of reading a JSON file named ‘data.json’ is shown below:
“`javascript
fs.readFile(‘data.json’, ‘utf8’, (err, data) => {
if (err) {
console.error(err);
return;
}
const jsonData = JSON.parse(data);
console.log(‘JSON content:’, jsonData);
});
“`
Reading CSV files requires the use of specialized libraries like ‘csv-parser’. An example of reading a CSV file named ‘data.csv’ using ‘csv-parser’ is demonstrated:
“`javascript
const csv = require(‘csv-parser’);
fs.createReadStream(‘data.csv’)
.pipe(csv())
.on(‘data’, (row) => {
console.log(‘CSV Row:’, row);
})
.on(‘end’, () => {
console.log(‘CSV file processing complete’);
});
“`
For reading binary files, you can use the fs.readFile() method to read the content as buffer data. An example of reading a binary file named ‘binaryFile.bin’ is given:
“`javascript
fs.readFile(‘binaryFile.bin’, (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(‘Binary data:’, data);
});
“`
In addition to reading files, Node.js also provides methods for writing data to files in different formats, including text files, JSON files, CSV files, and binary files. Understanding these methods is crucial for manipulating and storing information across diverse file types.
Source link