如何在 NodeJS 中将文件从 S3 存储桶上传到服务器(SFTP)?

How to upload file from S3 bucket to server (SFTP) in NodeJS?

我正在尝试在 NodeJS 中使用 ssh2-sftp-client 将文件从 AWS 中的 S3 存储桶发送到我的服务器。 我见过很多例子,我都试过了,但都没有成功。我觉得这个很接近但仍然不适合我:

async function sendFileViaSftp(srcEvent){
    let Client = require('ssh2-sftp-client');
    let Path = '/';

    let sftp = new Client();
    await sftp.connect({
        host: '73.XXX.XX.XXX', 
        port: 22,
        username: 'username',
        password: 'mypassword'
    }).then(() => {
        console.log("Connected...");
        return sftp.list(Path);
    }).then((list) => {
        console.log("It worked");
        console.log("file to transfer: " + srcEvent.file);
        var fs = require('fs');
        var path = require('path');

        var params = {
            Bucket: srcEvent.bucket,
            Key: srcEvent.key
        };

        var tempFileName = path.join('/tmp/', srcEvent.file);
        var tempFile = fs.createWriteStream(tempFileName);

        s3.getObject(params).createReadStream().pipe(tempFile);
        console.log("file is in tmp");

        let data = fs.createReadStream(tempFileName);
        let remote = '/';
        sftp.put(data, remote);
        console.log("the code makes it to here and prints this");
        

        return list;
    }).catch((err) => {
        console.log('Catch Error: ', err);
        throw new Error(err);
    });
}

我是这样调用这个函数的:

if (folder === 'something') {
        await sendFileViaSftp(srcEvent);
        return {
            statusCode: 200,
            body: srcEvent
        };
}

我没有收到任何错误消息,看起来它只是超时了,我不明白,因为我正在使用 async/await。在我的示例中,我试图从 S3 存储桶中提取文件,并将其存储在 /tmp/ 中,然后发送 /tmp/test.xlssrcEvent.file is test.xls in this case.

即使我可以简单地从这个函数向我的服务器发送一个空白的 txt 文件,那也会很有帮助。 谢谢!

我明白了。不确定问题到底出在哪里,但这会成功地从 S3 中提取文件,然后上传到 SFTP 服务器:

async function sendFileViaSftp(srcEvent) {
    let Client = require('ssh2-sftp-client');
    var path = require('path');

    var localFolder = "/tmp";
    var remoteFolder = "/complete";

    var localfile = path.join(localFolder, srcEvent.file);
    var remotePath = path.join(remoteFolder, srcEvent.file);
    getFileFromS3(srcEvent, localFolder);

    let sftp = new Client();
    await sftp.connect(sftpCredentials).then(() => {

            try {
                return sftp.fastPut(localfile, remotePath);
            } catch (err) {
                console.log("Could not upload file: " + err);
            }
        })
        .then(() => {
            console.log("ending connections");
            sftp.end();
        })
        .catch(err => {
            console.error(err.message);
        });
}

async function getFileFromS3(srcEvent, localFolder) {
    var params = {
        Bucket: srcEvent.bucket,
        Key: srcEvent.key
    };

    var tempFileName = path.join(localFolder, srcEvent.file);
    var tempFile = fs.createWriteStream(tempFileName);

    s3.getObject(params).createReadStream().pipe(tempFile);
    console.log("Put file in temp");

}