使用nodejs分块上传大文件

Upload large files in chunks using nodejs

我正在尝试将非常大的文件分块上传到服务器。服务器端工作得很好。在我提出的功能中,它会尝试一次上传所有文件。我是 async/await 的新手,不确定如何进行。目标是一次只上传一个块。

请注意,我已将其从 class 中删除,为清楚起见进行了更新,并删除了所有不必要的位。

使用 node-fetch 添加 fetch()。

感谢您的帮助或建议:)

let tree = []

const start = () => {
    scan('/foo/bar', err => { 
        tree.forEach(file => {
            upload(file)
        })
    })
}

const scan = dir => { ... } // assigns array of files to tree

const upload = file => {
    const stream = fs.createReadStream(file) 
    stream.on('data', async chunk => {
        stream.pause()
        try {
            let response = await fetch('https://some/endpoint', {
                method: 'post',
                body: JSON.stringify({
                    file: file,
                    chunk: chunk.toString('base64')
                }) 
            })
            stream.resume()
        } catch(e) {
            // handle errors
        }
    })
    stream.on('end', () => {
       console.log('end', file)
    })
    stream.on('error', err => {
        console.log('error', err)
    })
}

Array.prototype.forEach 同步运行,直到处理完数组的所有元素,丢弃它调用的参数函数返回的任何值。

要一次上传一个文件,请尝试使用 await(在异步函数内)等待每个文件上传,并结合上传过程中返回的承诺,该承诺在上传时实现已经完成。从概念上讲(没有优雅的错误处理)它可能看起来像

const uploadTree = async tree => {
    for( file of tree) {
         await uploadFile( file); // process files one at a time
    }
}

// wrap the existing upload code in a promise executor:

const uploadFile = file => new Promise( (resolve, reject) => {
     const stream = fs.createReadStream(file)
     stream.on('data' ...
        ...
     } catch(e) {
        console.log( "Error uploading chunk of %s", file)
        reject(e) // handle errors
     }
     stream.on('end', resolve)
     stream.on('error', e=> {
        console.log(" Error reading %s", file)
        reject (e)
     })
});

// upload complete tree array files:

uploadTree(tree)
.then( ()=> console.log( "tree uploaded successfully"));
.catch( err=> console.log("An upload failed: ", err));