gpt4 book ai didi

javascript - Node FTP不执行 `once(' close')`下载文件大时的回调

转载 作者:搜寻专家 更新时间:2023-10-31 22:54:02 25 4
gpt4 key购买 nike

我有一种从 FTP 服务器下载文件的方法,它可以很好地处理较小的文件,但是当我用它来下载 ~5GB 大小的 zip 类型的文件时,它会下载它,但之后它什么都不做.当下载达到 100% 时,脚本不会继续。如果下载完成后它实际上在后台执行某些操作,我应该等待吗?有文件大小限制吗?

const FTP = require('ftp')

可在 npm 上找到

downloadFile: params => {
return new Promise((resolve, reject) => {
let ftpClient = new FTP()
let total = params.state.fileSize
let progress = 0
ftpClient.on('ready', _ => {
console.log(`Downloading ${params.targetedFile} ...`);
ftpClient.get(params.targetedFile, (err, stream) => {
if (err) reject(err)
stream.on('data', buffer => {
progress += buffer.length
process.stdout.write(`Progress: ${(progress/total*100).toFixed(2)}% (${progress}/${total}) \r`)
})
stream.once('close', _ => {
ftpClient.end()
console.log(`Saved downloaded file to ${params.localDir}`);
resolve(params.localDir)
})
stream.pipe(fs.createWriteStream(params.localDir))
})
})
ftpClient.connect(params.auth)
})
}

基本上,下载大文件时不会执行 stream.once('close', ...) 的回调。并且它会针对相同类型的较小文件执行。

最佳答案

我建议您处理关闭写入流的事件。

原因很简单:我们从 ftp 的读取流和管道读取到写入流,一切正常,当文件成功关闭时。

所以代码:

downloadFile: params => {
return new Promise((resolve, reject) => {
let ftpClient = new FTP()
let total = params.state.fileSize
let progress = 0
ftpClient.on('ready', _ => {
console.log(`Downloading ${params.targetedFile} ...`);
ftpClient.get(params.targetedFile, (err, stream) => {
if (err) {
ftpClient.end();
return reject(err);
}

stream.on('data', buffer => {
progress += buffer.length
process.stdout.write(`Progress: ${(progress/total*100).toFixed(2)}% (${progress}/${total}) \r`)
});

// opening writeStream to file
let finished = false;
const writeStream = fs.createWriteStream(params.localDir);

writeStream.on('finish', (result) => { // handling finish
finished = true;
ftpClient.end();
console.log(`Finish triggered ${params.localDir}`);
console.log(result);
resolve(params.localDir);
});

writeStream.on('close', (result) => { // handling close
ftpClient.end();
console.log(`Close triggered ${params.localDir}`);
console.log(result);
resolve(params.localDir);
})

// piping readStream to writeStream
stream.pipe(writeStream);
})
})
ftpClient.connect(params.auth)
})
}

关于javascript - Node FTP不执行 `once(' close')`下载文件大时的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43635941/

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