ru
//實行文件操作 //文件寫入 //1.加載文件操作,fs模塊 var fs = require('fs'); //2.實現文件寫入操作 var msg='Hello world'; //調用fs.writeFile() 進行文件寫入 fs.writeFile('./hello.text',msg,'utf8',function(err){ //如果err=null,表示文件使用成功,否則,表示希爾文件失敗 if(err) console.log('寫文件出錯了,錯誤是:'+err); else console.log('ok'); })
成功
下面是文件讀取
/* //實行文件操作 //文件寫入 //1.加載文件操作,fs模塊 var fs = require('fs'); //2.實現文件寫入操作 var msg='Hello world'; //調用fs.writeFile() 進行文件寫入 fs.writeFile('./hello.txt',msg,'utf8',function(err){ //如果err=null,表示文件使用成功,否則,表示希爾文件失敗 if(err) console.log('寫文件出錯了,錯誤是:'+err); else console.log('ok'); }) */ //實現文件讀取操作 //1.加載fs模塊 var fs=require('fs'); //2.調用fs.readFile(file[,options],callback)file是文件文件名,options是編碼如utf8,callback是回調函數 fs.readFile('./hello.txt',function(err,data){ if(err){ console.log('err'); } //data參數的數據類型是Buffer對象,里面保存的是一個個字節(理解為字節組) console.log("data:",data); //把Buffer對象轉換為字符串,調用toString(utf8)方法 console.log("data.toString('utf8'):",data.toString('utf8')); //toString()里可以不加utf8 console.log("data.toString():",data.toString()); }) //如果fs.readFile('./hello.txt','utf8',function(err,data){ //這里函數就可以不用toString(),data默認轉換為字符串 //}
結果如上