Hot For Coding
NodeJS读写文件

NodeJS中读写文件基本都是用fs模块,应该是file system的缩写

读文件

读文件有两个API,差别就是一个是同步另一个异步

  • fs.readFile
  • fs.readFileSync
// Nicholas Lee 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
// Nicholas Lee 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")

TITLE: NodeJS读写文件

LINK: https://www.qttc.net/79_nodejs_write_read_file.html

NOTE: 转载内容请注明出处