V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
dxcqcv
V2EX  ›  Node.js

是否可以用 node 的 stream 来读并改写最后写入到同一个文件?

  •  1
     
  •   dxcqcv · 2017-10-02 08:07:02 +08:00 · 3181 次点击
    这是一个创建于 2369 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我现在的做法是多创建一个临时文件,然后删除原文件,重命名临时文件,我想知道有没有更好的办法来实现用 node 流来改写同文件?

    代码如下

    const rm = require('rimraf')
    const through2 = require('through2')
    const fs = require('graceful-fs')
    // source file path
    const replacementPath = `./static/projects/${destPath}/index.html`
    // temp file path
    const tempfilePath = `./static/projects/${destPath}/tempfile.html`
    // read source file then write into temp file
    await promiseReplace(replacementPath, tempfilePath)    
    // del the source file
    rm.sync(replacementPath)
    // rename the temp file name to source file name
    fs.renameSync(tempfilePath, replacementPath)
    // del the temp file
    rm.sync(tempfilePath)
    
    // promiseify readStream and writeStream
    function promiseReplace (readfile, writefile) {
      return new Promise((res, rej) => {
        fs.createReadStream(readfile)
          .pipe(through2.obj(function (chunk, encoding, done) {
            const replaced = chunk.toString().replace(/id="wrap"/g, 'dududud')
            done(null, replaced)
          }))
          .pipe(fs.createWriteStream(writefile))
          .on('finish', () => {
            console.log('replace done')
            res()
          })
          .on('error', (err) => {
            console.log(err)
            rej(err)
          })
      })
    }
    
    1 条回复    2017-10-04 01:01:03 +08:00
    qiuyk
        1
    qiuyk  
       2017-10-04 01:01:03 +08:00
    应该是不行的 要么全读进内存 要么创建临时文件
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2024 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:17 · PVG 00:17 · LAX 09:17 · JFK 12:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.