gpt4 book ai didi

node.js - 同步流输出

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:35 26 4
gpt4 key购买 nike

我正在努力将不同大小的图像上传到亚马逊 s3 存储。每当我上传图像时,我都会创建三个独立的可读图像流,并将其通过管道传输到我的缩放器函数和 s3 上传函数。

每个流都会将不同大小的图像上传到 s3 云。我希望同步流的输出,以便在所有三个流中都完成上传后,我可以发送已上传照片的 URL。

我无法知道我的所有直播何时结束。或者我如何等​​到所有流都结束然后返回所有上传图像的 URL?

这是我的代码

调整大小.js

import fs from 'fs';
import sharp from 'sharp';

export const resizeThumbnail = function (path, format) {
const readStream = fs.createReadStream(path);
let transform = sharp();
if (format) {
transform = transform.toFormat(format);
}
transform = transform.resize(100);
return readStream.pipe(transform);
};

export const resizeLowRes = function (path, format) {
const readStream = fs.createReadStream(path);
let transform = sharp();
if (format) {
transform = transform.toFormat(format);
}
transform = transform.resize(500);
return readStream.pipe(transform);
};

export const resizeHighRes = function (path, format) {
const readStream = fs.createReadStream(path);
let transform = sharp();
if (format) {
transform = transform.toFormat(format);
}
transform = transform.resize(1080);
return readStream.pipe(transform);
};

resizer.js

import { resizeThumbnail, resizeLowRes, resizeHighRes } from './resize';
import awsConfig from '../config/awsConfig';
import { uploadFromStream } from './amazonS3';

// receives a list of images
export const resizer = (images, id, callback) => {
const imageList = images.split(',');
const store = [];
imageList.forEach((imagePath, i) => {
sizeCreator(imagePath, id, i, (err, localstore) => {
if (!err) {
store.push(localstore);
console.log(store);
}
callback(err);
});
});
};

const sizeCreator = (imagePath, id, i, callback) => {
const localstore = {};
resizeThumbnail(imagePath).pipe(uploadFromStream(awsConfig, id, i, 'thumbnail', (err, data) => {
localstore.thumbnail = {
url: data.Location,
filename: data.key,
};
}));
resizeLowRes(imagePath).pipe(uploadFromStream(awsConfig, id, i, 'lowres', (err, data) => {
localstore.lowres = {
url: data.Location,
filename: data.key,
};
}));
resizeHighRes(imagePath).pipe(uploadFromStream(awsConfig, id, i, 'highres', (err, data) => {
localstore.highres = {
url: data.Location,
filename: data.key,
};
callback(err, localstore);
}));
};

amazonS3.js

import stream from 'stream';

export const uploadFromStream = (s3, id, index, res, callback) => {
const pass = new stream.PassThrough();
const params = {
Bucket: 'Bucket',
Key: `${id}_${res}_${index}`,
Body: pass,
ContentType: 'image/jpeg',
};
s3.upload(params, (err, data) => {
callback(err, data);
});
return pass;
};

最佳答案

您可以对开始的流进行计数并更新结束流事件的计数器。当最后一个流完成时,计数器的值应为 0。然后您可以触发发送 url 的不同事件。

关于node.js - 同步流输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54711424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com