Node.js-AWS-程序在上载到S3存储桶完成之前终止 [英] Node.js - AWS - Program Terminates Before Upload to S3 Bucket Completes

查看:155
本文介绍了Node.js-AWS-程序在上载到S3存储桶完成之前终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个创建HTML文件的程序.然后,我尝试在程序结束时将文件上传到我的S3存储桶.看来问题出在我的程序在允许该函数完成或从该函数接收回调之前终止.

I've written a program that creates HTML files. I then attempt to upload the files to my S3 bucket at the end of the program. It seems that the problem is that my program terminates before allowing the function to complete or receiving a callback from the function.

这是我代码的要旨:

let aws = require('aws-sdk');

aws.config.update({
    //Censored keys for security
    accessKeyId: '*****',
    secretAccessKey: '*****',
    region: 'us-west-2'
});

let s3 = new aws.S3({
    apiVersion: "2006-03-01",
});

function upload(folder, platform, browser, title, data){
    s3.upload({
        Bucket: 'html',
        Key: folder + platform + '/' + browser + '/' + title + '.html',
        Body: data
    },  function (err, data) {
        if (err) {
            console.log("Error: ", err);
        }
        if (data) {
            console.log("Success: ", data.Location);
        }
    });
}

/*
*
* Here is where the program generates HTML files
*
*/

upload(folder, platform, browser, title, data);

如果在代码的HTML生成部分之前调用upload()函数(配置有测试/虚拟数据),则上传成功.测试文件成功上传到S3.但是,在代码末尾调用该函数时,没有收到错误或成功响应.相反,该程序只是终止而文件没有上载到S3.

If I call the upload() function (configured with test/dummy data) before the HTML generation section of my code, the upload succeeds. The test file successfully uploads to S3. However, when the function is called at the end of my code, I do not receive an error or success response. Rather, the program simply terminates and the file isn't uploaded to S3.

在继续执行程序之前,是否可以等待upload()函数的回调?在将文件上传到S3之前如何防止程序终止?谢谢!

Is there a way to wait for the callback from my upload() function before continuing the program? How can I prevent the program from terminating before uploading my files to S3? Thank you!

实施Deiv的答案后,我发现程序 still 仍未上传我的文件.我仍然没有收到任何成功或错误消息.实际上,该程序似乎只是跳过了upload()函数.为了测试这一点,我在调用upload()之后添加了console.log("test")来查看它是否可以执行.果然,日志成功打印.

After implementing Deiv's answer, I found that the program is still not uploading my files. I still am not receiving a success or error message of any kind. In fact, it seems like the program just skips over the upload() function. To test this, I added a console.log("test") after calling upload() to see if it would execute. Sure enough, the log prints successfully.

这里有关于该项目的更多信息:我正在使用WebdriverIO v4创建有关通过/失败的各种测试的HTML报告.我通过多个事件侦听器(例如this.on('test:start')this.on('suite:end')等)收集测试结果.最后一个事件是this.on('end'),当所有测试完成执行时将调用该事件.这里是根据运行测试的操作系统,浏览器等对测试结果进行排序的方法.

Here's some more information about the project: I'm utilizing WebdriverIO v4 to create HTML reports of various tests passing/failing. I gather the results of the tests via multiple event listeners (ex. this.on('test:start'), this.on('suite:end'), etc.). The final event is this.on('end'), which is called when all of the tests have completed execution. It is here were the test results are sorted based on which Operating System it was run on, Browser, etc.

我现在注意到即使我将程序放在处理程序的最开始,我的程序也不会在this.on('end')事件处理程序中执行与S3相关的任何操作,尽管我仍然确信这是因为它不是.给了足够的执行时间,因为处理程序能够处理结果并非常快速地创建HTML文件.我有这段代码列出了我的S3中的所有存储桶:

I'm now noticing that my program won't to do anything S3 related in the this.on('end') event handler even if I put it at the very beginning of the handler, though I'm still convinced it's because it isn't given enough time to execute because the handler is able to process the results and create HTML files very quickly. I have this bit of code that lists all buckets in my S3:

s3.listBuckets(function (err, data) {
    if (err) {
        console.log("Error: ", err);
    } else {
        console.log("Success: ", data.Buckets);
    }
});

即使在this.on('end')开头运行时,也不会返回任何结果.有人有什么想法吗?我真的很为难.

Even this doesn't return a result of any kind when run at the beginning of this.on('end'). Does anyone have any ideas? I'm really stumped here.

这是实现Naveen建议的新代码:

Here is my new code which implement's Naveen's suggestion:

this.on('end', async (end) => {

/*
* Program sorts results and creates variable 'data', the contents of the HTML file.
*/

    await s3.upload({
        Bucket: 'html',
        Key: key,
        Body: data
    }, function (err, data) {
        if (err) {
            console.log("Error: ", err);
        }
        if (data) {
            console.log("Success: ", data.Location);
        }
    }).on('httpUploadProgress', event => {
        console.log(`Uploaded ${event.loaded} out of ${event.total}`);
    });
}

逻辑看起来不错,但是仍然没有收到成功或错误消息,并且看不到上传进度. HTML文件未上传到S3.

The logic seems sound, but still I get no success or error message, and I do not see the upload progress. The HTML file does not get uploaded to S3.

推荐答案

您可以使用promises等待上传功能完成.它将是这样的:

You can use promises to wait for your upload function to finish. Here's what it will look like:

function upload(folder, platform, browser, title, data) {
    return new Promise((resolve, reject) => {
        s3.upload({
            Bucket: 'html',
            Key: folder + platform + '/' + browser + '/' + title + '.html',
            Body: data
        }, function(err, data) {
            if (err) {
                console.log("Error: ", err);
                return reject(err);
            }
            if (data) {
                console.log("Success: ", data.Location);
                return resolve();   //potentially return resolve(data) if you need the data
            }
        });
    });
}

/*
*
* Here is where the program generates HTML files
*
*/

upload(folder, platform, browser, title, data)
    .then(data => { //if you don't care for the data returned, you can also do .then(() => {
        //handle success, do whatever else you want, such as calling callback to end the function
    })
    .catch(error => {
        //handle error
    }

这篇关于Node.js-AWS-程序在上载到S3存储桶完成之前终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆