【问题标题】:copy an image in nodeJs with fs使用 fs 在 nodeJs 中复制图像
【发布时间】:2020-04-23 03:09:07
【问题描述】:

我试图将 png 文件从一个文件夹复制到我的 nodeJs 项目中的另一个文件夹。我遇到了一些问题。新图像文件有问题,无法打开。 我用这个代码

const  fs = require('fs');

     var inStr = fs.createReadStream(mainDir+"/"+req.body.ExRequestId+".png");

        var outStr = fs.createWriteStream(mainDir+"/"+docReq._id + ".png");

        inStr.pipe(outStr);

【问题讨论】:

  • this尝试第二种方法。如果同样的问题仍然存在,那么我猜你的原始图像本身有问题。
  • @AjayDabas 我尝试过,但不起作用。新图像为空
  • 您使用的是什么版本的 Node?节点从节点 8.5.0 添加了copyFile 过程。尝试改用它。查看here 了解如何操作。
  • @ArminTaghavizad v11.0.9 当我使用 copyFile 时,它​​完成但它是空的并且没有任何数据来显示图像
  • 如果你使用的是低版本的 node fs 模块的包。 npmjs.com/package/fs-extra。这是一个非常常见和流行的包。

标签: node.js npm fs


【解决方案1】:

使用流时,最好等待流准备好后再使用它们并处理错误。

以下 sn-p 等待两个流上的 ready 事件,然后将 ReadStream 管道传输到 WriteStream 并处理错误。

// assuming you're using express and the app instance is bound to a variable named app

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

// ...

// helper function: returns a promise that gets resolved when the specified event is fired
const waitForEvent = (emitter, event) => new Promise((resolve, reject) => emitter.once(event, resolve));

app.post('/handle-post', async (req, res) => {
    // TODO: validate the input
    const { ExRequestId } = req.body;

    const srcFileName = `${path.join(mainDir, ExRequestId)}.png`;
    const destFileName = `${path.join(mainDir, docReq._id)}.png`;

    const srcStream = fs.createReadStream(srcFileName);    
    await waitForEvent(srcStream, "ready");
    const destStream = fs.createWriteStream(destFileName);    
    await waitForEvent(destStream, "ready");

    const handleError = err => res.status(500).json(err);
    srcStream.on("error", handleError);
    destStream.on("error", handleError);

    srcStream.pipe(destStream);
    await waitForEvent(srcStream, 'end');

    res.status(200).json({srcFileName, destFileName});
});

我还整理了一个最小的工作示例。可以找到here

【讨论】:

    【解决方案2】:

    试试这个代码:

    fs.readFile(sourcePath , function (err, data) {
     if (err) throw err;
     fs.writeFile(destinationPath , data , 'base64' , function (err) {
      if (err) throw err;
       console.log('It\'s saved!');
     });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-17
      • 2021-09-15
      • 2021-05-04
      • 2020-06-20
      • 2017-04-07
      • 2016-02-02
      • 2018-11-13
      • 2014-04-08
      相关资源
      最近更新 更多