出于可靠性原因,我将一些图像从外部源传输到 Amazon S3 存储。
但是,图像被截断,如下图所示。
我使用的代码具有以下逻辑:
const request = require('request');
let r = request(pictureUrl);
r.on('response', function(rs){
let newFileName = new Date().getTime() + '_' + externalId+'.jpg';
let localPath = __dirname+'/../../temp_files/'+newFileName+'';
let ws = fs.createWriteStream(localPath);
rs.pipe(ws);
rs.on('end', function(){
fs.readFile(localPath, (error, fileContent) => {
uploadToS3(fileContent, newFileName, 'profile_pics', function (err, response) {
fs.unlink(localPath, (err) => {
/* send response to browser */
我认为造成这种情况的原因是以下之一:
1. r.on('response'
<- 文件尚未收到,下一个流程开始。
2. rs.on('end'
<- 文件尚未写入本地,下一个进程开始。
3. fs.unlink(localPath
<- 在 uploadToS3(fileContent
完成之前执行。
意见?
最佳答案
您应该在 finish 的回调中将文件上传到 S3可写流的事件。
ws.on('finish', function(){
fs.readFile(localPath, (error, fileContent) => {
uploadToS3(fileContent, newFileName, 'profile_pics', function (err, response) {
...
关于假设 #2,你是正确的
- rs.on('end' <- the file is not written locally yet and the next processes start.
其他假设都是错误的。
- r.on('response' <- the file is not received yet and the next processes start.
#1 并不重要。多个回调应该能够并行运行。
- fs.unlink(localPath <- is executed before uploadToS3(fileContent is completed.
#3 可能是错误的。我不确定 uploadToS3
的作用,但可能它会在上传完成时调用回调,因此此后文件取消链接
关于node.js - 从 NodeJS 到 Amazon S3 的不完整文件复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097809/