在Node.js中,我们可以使用内置的fs模块来进行文件的读写操作。以下是一些常用的文件读写方法:
- 使用
fs.readFile()方法读取文件:
const fs = require('fs');
fs.readFile('/path/to/file', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
- 使用
fs.readFileSync()方法同步读取文件:
const fs = require('fs');
try {
const data = fs.readFileSync('/path/to/file', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
- 使用
fs.writeFile()方法写入文件:
const fs = require('fs');
fs.writeFile('/path/to/file', 'Hello World!', (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
- 使用
fs.writeFileSync()方法同步写入文件:
const fs = require('fs');
try {
fs.writeFileSync('/path/to/file', 'Hello World!');
console.log('The file has been saved!');
} catch (err) {
console.error(err);
}
- 使用
fs.appendFile()方法追加文件内容:
const fs = require('fs');
fs.appendFile('/path/to/file', 'Additional data', (err) => {
if (err) throw err;
console.log('The data is appended to the file!');
});
- 使用
fs.appendFileSync()方法同步追加文件内容:
const fs = require('fs');
try {
fs.appendFileSync('/path/to/file', 'Additional data');
console.log('The data is appended to the file!');
} catch (err) {
console.error(err);
}
以上代码展示了如何使用Node.js的fs模块进行文件的读写操作。其中,异步方法(如fs.readFile()和fs.writeFile())不会阻塞程序的执行,而同步方法(如fs.readFileSync()和fs.writeFileSync())会阻塞直到操作完成。在实际应用中,根据需要选择适当的方法。