node.js - 从 NodeJS 到 Amazon S3 的不完整文件复制

标签 node.js express amazon-s3

出于可靠性原因,我将一些图像从外部源传输到 Amazon S3 存储。

但是,图像被截断,如下图所示。
我使用的代码具有以下逻辑:

const request = require('request');
let r = request(pictureUrl);
r.on('response', function(rs){
  let newFileName = new Date().getTime() + '_' + externalId+'.jpg';
  let localPath = __dirname+'/../../temp_files/'+newFileName+'';
  let ws = fs.createWriteStream(localPath);
  rs.pipe(ws);
  rs.on('end', function(){
    fs.readFile(localPath, (error, fileContent) => {
      uploadToS3(fileContent, newFileName, 'profile_pics', function (err, response) {
        fs.unlink(localPath, (err) => {

           /* send response to browser */

我认为造成这种情况的原因是以下之一:
1. r.on('response' <- 文件尚未收到,下一个流程开始。
2. rs.on('end' <- 文件尚未写入本地,下一个进程开始。
3. fs.unlink(localPath <- 在 uploadToS3(fileContent 完成之前执行。

意见?

'Incomplete image copy'

最佳答案

您应该在 finish 的回调中将文件上传到 S3可写流的事件。

ws.on('finish', function(){
    fs.readFile(localPath, (error, fileContent) => {
      uploadToS3(fileContent, newFileName, 'profile_pics', function (err, response) {
...

关于假设 #2,你是正确的

  1. rs.on('end' <- the file is not written locally yet and the next processes start.

其他假设都是错误的。

  1. r.on('response' <- the file is not received yet and the next processes start.

#1 并不重要。多个回调应该能够并行运行。

  1. fs.unlink(localPath <- is executed before uploadToS3(fileContent is completed.

#3 可能是错误的。我不确定 uploadToS3 的作用,但可能它会在上传完成时调用回调,因此此后文件取消链接

关于node.js - 从 NodeJS 到 Amazon S3 的不完整文件复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097809/

相关文章:

amazon-web-services - AWS CLI移动文件,路径中带有通配符(星号)

javascript - 了解strapi关系如何运作

node.js - 如何在dynamodb中插入json

mysql - 取消嵌套 Node 数据库调用

node.js - npm 脚本按顺序与expressjs

ubuntu - 如何使用 Minio 作为 BindFS 挂载的前端

java - SPARK 驱动程序在读取多个 S3 文件时内存不足

Javascript/Nodejs 检查某些内容是否为 bigint 类型?

node.js - nodejs Async.each 嵌套循环 困惑

javascript - 当路由参数为某个值时如何添加自定义路由来表达