在Node.js中,我们通常使用内置的fs(文件系统)模块来读取和写入文件。以下是一些常用的函数和例子:
1. 读取文件
fs.readFile(path[, options], callback): 异步读取文件的全部内容。
fs.readFileSync(path[, options]): 同步读取文件的全部内容。
const fs = require('fs');
// 异步读取
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 同步读取
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
2. 写入文件
fs.writeFile(file, data[, options], callback): 异步写入文件,如果文件已存在,则覆盖文件。
fs.writeFileSync(file, data[, options]): 同步写入文件,如果文件已存在,则覆盖文件。
fs.appendFile(file, data[, options], callback): 异步追加内容到文件末尾。
fs.appendFileSync(file, data[, options]): 同步追加内容到文件末尾。
const fs = require('fs');
// 异步写入
const data = 'Hello, world!';
fs.writeFile('output.txt', data, (err) => {
if (err) throw err;
console.log('File has been saved!');
});
// 同步写入
try {
fs.writeFileSync('output.txt', 'Hello again!');
console.log('File has been saved!');
} catch (err) {
console.error(err);
}
// 异步追加
fs.appendFile('output.txt', '\nThis is appended text.', (err) => {
if (err) throw err;
console.log('Text has been appended!');
});
// 同步追加
try {
fs.appendFileSync('output.txt', '\nThis is more appended text.');
console.log('More text has been appended!');
} catch (err) {
console.error(err);
}
注意:在使用fs模块时,要确保文件路径是正确的,否则可能会导致错误。同时,对于大型文件,建议使用流(stream)来处理,以提高性能和效率。