我正在尝试调整照片的大小并同步上传到服务器。我相信关键将是使流功能同步。
let str = '"This" is my "new" key "string"';
let strArray = str.split("");
let open = true;
for (let i = 0; i < strArray.length; ++i) {
if (strArray[i] == '"') {
if (open === true) {
strArray[i] = '{';
}
else {
strArray[i] = '}';
}
open = (open == true) ? false : true;
}
}
str = strArray.join("");
console.log(str)
答案 0 :(得分:3)
在NodeJS中执行同步操作是不好-在同步方法结束时,它会停止处理事件队列。
据我了解,您将“ 同步”命名为具有回调。
将流转换为承诺怎么样?
const downloadAndResizePhotoByUrl = (photoUrl, size) => {
return new Promise((resolve, reject) => {
gm(request(photoUrl))
.resize(size[0], size[1])
.streamFn((error, stdout, stderr) => {
if(error) return reject(error);
let buffer = Buffer.from('');
stdout.on('data', data => {
buffer = Buffer.concat([buffer, data]);
});
stdout.on('end', () => resolve(buffer));
stdout.on('error', error => reject(error));
});
});
}
const uploadPhotoFromUrlToS3 = async (photoUrl, uploadAs, size, cb) => {
try {
const data = await downloadAndResizePhotoByUrl(photoUrl, size);
uploadToServerSynchronous(
{
Bucket: config.s3_bucket_photos,
Key: uploadAs,
Body: Buffer.from(data),
ACL: 'public-read',
ContentType: "image/jpeg"
},
cb
);
}
catch (error) {
cb(error);
}
}