nodejs中文件讀取寫入兩種方法封裝


方法一:利用回調函數

const fs = require('fs')
const path = require('path')

const fileHelper = {
    readFile:(path,cb)=>{
        fs.readFile(path,{encoding:'utf8'},(err,data)=>{
            if(!err){
                cb(data)
            }
        })
    },
    writeFile:(path,content,cb)=>{
        fs.writeFile(path,content,{encoding:'utf8'},(err)=>{
            if(!err){
                cb();
            }
        })
    }
}

const testPath = path.join(__dirname,'SubscribeMsg.js')
fileHelper.readFile(testPath,(data)=>{
    console.log(data)
})

const testwrite = path.join(__dirname,'hello.json')
fileHelper.writeFile(testwrite,'{ok:ok}',()=>{
    console.log('寫入成功')
})

注意:當嵌套過深的時候,十分不方便,可以用Promise改造const fs = require('fs').promises可以用一個支持Promises的fs對象

使用Promise進行文件讀取寫入操作

const fs = require('fs').promises
const path = require('path')

const fileHelper = {
    readFile:(path)=>{
        return fs.readFile(path,{encoding:'utf8'})
    },
    writeFile:(path,content)=>{
        return fs.writeFile(path,content,{encoding:'utf8'})
    }
}


const testPath = path.join(__dirname,'SubscribeMsg.js')
fileHelper.readFile(testPath).then((data)=>{
    console.log(data)
})
const testwrite = path.join(__dirname,'hello.json')
fileHelper.writeFile(testwrite,'{ok:ok}').then(()=>{
    console.log('ok')
})


免責聲明!

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



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