node——文件寫入,文件讀取


 
         

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默認轉換為字符串
//}

 

 結果如上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM