读文件
require('fs')
//使用require方法加载fs这个核心模块
fs.readFile(file,function)
//第一个参数:要读取的文件路径 //第二个参数:一个回调函数
//
// 成功: // data 数据 // error null // 失败: // data null undefined没有大数据 // error 错误对象
1 var fs=require('fs') 2 fs.readFile('./data/hello.txt',function(error,data){ 3 if (error) { 4 console.log("读取文件失败") 5 return 6 }else{ 7 console.log(data.toString()) 8 } 9 })
写文件
fs.writeFile(file,data,function)
//第一个参数:要写入的文件路径 //第二个参数:要写入的内容 //第三个参数:回调函数
1 var fs=require('fs') 2 var data="写文件。\n大家好,我是Node.js" 3 fs.writeFile('./data/你好.md',data,function(error){ 4 if(error){ 5 console.log("写入文件失败!") 6 return 7 } 8 console.log("文件写入成功") 9 })