NodeJS中读写文件基本都是用fs模块,应该是file system
的缩写
读文件
读文件有两个API,差别就是一个是同步另一个异步
fs.readFile
fs.readFileSync
// 琼台博客 www.qttc.net
// fs.readFile
var fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, 'index.md');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (!err) {
console.log('received data: ' + data);
} else {
console.log(err);
}
});
// fs.readFileSync
var data = fs.readFileSync(filePath, {encoding: 'utf-8'});
console.log('received data: ' + data);
写文件
写文件也有两个API,一个同步另一个异步
fs.writeFile
fs.writeFileSync
// 琼台博客 www.qttc.net
// fs.writeFile
var fs = require('fs');
fs.writeFile("index.md", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
// fs.writeFileSync
fs.writeFileSync("index.md", "Hey there!", "utf-8")