• 文件系统模块1(导入,写入)


    1导入fs模块

    const fs = require('fs')

    2,读取文件内容

    fs.readFlie(path,'utf8',function(err,dataStr){
    console.log(err)
    console.log('-----')
    console.log(dataStr)
    })

    注:path为文件路径,成功err为null,失败err为错误对象,dataStr为undefined

    3,powerShell输出:node 文件路径

    优化版:

    fs.readFlie('path','utf8',function(err,dataStr){
    if(err){
    return console.log('读取失败'+err.message)
    }
    console.log('读取成功'+err.message)
    })

      4,写入内容

    fs.writeFile('path','写入内容',function(err,dataStr){
        if(err){
            return console.log('写入失败'+err.message)
        }
        console.log('写入成功'+err.message)
    })
    

      5,案例

    const fs = require('fs')
    fs.readFlie('__dirname + path','utf8',function(err,dataStr){
      if(err){
        return console.log('读取失败'+err.message)
      }
    //切割数组,替换字符串
    const arrli = dataStr.split(' ')
    const arrNew = []
    arrli.forEach(item=>(
      arrNew.push(itemm.replace('=',':'))
      ))
      const nerStr = arrNew.join('\r\n')
      console.log(newStr)
    //调用fs.writeFile方法写入新文件
      fs.writeFile('__dirname + path',newStr,function(err){ 
      if(err){ 
      return console.log('写入失败'+err.message)
      }
      console.log('写入成功'+err.message)
    })
    })
    

      

  • 相关阅读:
    我容易么?
    意译和音译
    请教博客园高手:msn老是掉线的问题
    超市里最安全的食品
    两类人
    只要牵了手,就请不要轻易的说分手
    Palm Treo 650 .VS. Dopod P800
    强烈推荐一健康食品:紫红薯
    年底三篇
    奶奶,走好!
  • 原文地址:https://www.cnblogs.com/wencaiguagua/p/16804629.html
Copyright © 2020-2023  润新知