递归上传文件到S3,如何检测完成?

时间:2018-03-14 18:02:58

标签: node.js asynchronous amazon-s3

稍微帮助我使用Node.JS

构建了一个S3上传器

这一切都运行良好,文件到达那里,它们设置正确并拥有正确的权限,但我很难知道如何检测流程是否已完成。

const async = require('async');
const AWS = require('aws-sdk');
const mime = require('mime');
const fs = require('fs');
const path = require("path");
require('dotenv').config();

const uploadDirToS3 = function(uploadPath) {
  // instantiate aws object for s3
  var s3 = new AWS.S3();

  // async version
  function walk(currentDirPath, callback) {
    fs.readdir(currentDirPath, function (err, files) {
      if (err) {
        throw new Error(err);
      }
      files.forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
          callback(filePath, stat);
        } else if (stat.isDirectory()) {
          walk(filePath, callback);
        }
      });
    });
  }

  walk(uploadPath, function(filePath) {
    fs.readFile(filePath, function (err, data) {

      if (err) { throw err; }

      // get content-type (html,jpeg,gif,etc...)
      var metaData = mime.getType(filePath)

      // set bucket, key (filename), body (file),
      // public read-only and content-type
      var params = {
        Bucket: process.env.AWS_BUCKET,
        Key: filePath,
        Body: data,
        ACL: 'public-read',
        ContentType: metaData
      };

      // upload file to s3
      s3.putObject(params, function(err, data) {
         if (err) {
           console.log(err)
         } else {
           console.log("Successfully uploaded "+filePath);
         }
      });
    });
  })
}

uploadDirToS3("./media/media-1517245218111")

它确实是一个检查回调是否存在并且“突破”的情况;' ......走出循环?

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要使用 IterateOver Pattern

找到要复制的文件时,增加一个变量,完成S3复制后,跟踪另一个复制的变量。

当totalfind == totalcopied时,然后从调用函数启动回调。

df.assign(dh=[h[t.hour] for t, h in df.values])

             datetime  dh
0 2018-01-01 00:00:00  48
1 2018-01-01 01:00:00  46
2 2018-01-01 02:00:00  44
3 2018-01-01 03:00:00  42
4 2018-01-01 04:00:00  40
...

希望它有所帮助。

相关问题