📅  最后修改于: 2023-12-03 14:57:09.444000             🧑  作者: Mango
在Javascript中,我们经常需要进行文件操作,例如读取/写入文件、删除/移动文件等等。在Node.js中,这一过程由fs模块(文件系统)负责。
要使用fs模块,首先需要在代码中引入它:
const fs = require('fs');
读取文件是最常见的文件操作之一。我们可以使用fs.readFile()方法来读取文件。该方法接受三个参数:文件路径、编码方式以及回调函数。
fs.readFile('filePath', 'utf8', function(err, data) {
if (err) console.log(err);
console.log(data);
});
要写入文件内容,可以使用fs.writeFile()方法。该方法也接受三个参数:文件路径、写入的内容以及回调函数。
fs.writeFile('filePath', 'content', function(err) {
if (err) console.log(err);
console.log('File saved!');
});
如果文件不存在,fs.writeFile()方法会创建一个新文件并写入内容。
要删除文件,可以使用fs.unlink()方法。该方法接受一个参数:要删除的文件路径。
fs.unlink('filePath', function(err) {
if (err) console.log(err);
console.log('File deleted!');
});
要移动文件或者重命名文件,可以使用fs.rename()方法。该方法接受两个参数:源文件路径和目标文件路径。
fs.rename('oldPath', 'newPath', function(err) {
if (err) console.log(err);
console.log('File moved/renamed!');
});
以上介绍了fs模块的一些常见用法。除此之外,fs模块还有许多其他常用的方法,例如创建目录、遍历目录等等。在开发过程中,需要灵活运用fs模块的各种方法,以便更好地进行文件操作。