Node.js环境下为MinIO设置8MB/s上传速度限制的问题
解决MinIO上传限速不生效的问题
你之前用speed-limiter和bandwidth-throttle-stream没生效,核心原因是**fPutObject是MinIO SDK内部封装好的文件上传方法,它直接处理文件读取和上传的全流程,没有暴露中间的数据流接口**,导致你添加的限速工具无法接入上传链路。
要实现限速,需要改用putObject方法(支持传入自定义可读流),把文件读取流、限速流拼接后再传入上传。以下是修改后的完整代码:
const chokidar = require('chokidar') const notifier = require('node-notifier') const Minio = require('minio') const fs = require('fs') const { Throttle } = require('bandwidth-throttle-stream') const minio = new Minio.Client({ endPoint: '${dns-example}', port: 9000, useSSL: false, accessKey: '${user-example}', secretKey: '${pass-example}' }) const metaData = { 'Content-Type': 'application/octet-stream', 'X-Amz-Meta-Testing': 1234, 'example': 5678 } chokidar.watch('/Users/glichester/Movies', {ignoreInitial: true}).on('add', path => { notifier.notify({ title: 'New clip saved', message: `Clip: ${path.slice(24)}`, icon: 'icon.png', sound: true, appID: "Clip saver" }) // 监听文件变化,上传一次后取消监听避免重复触发 chokidar.watch(path).once('change', async file => { try { // 设置限速为8MB/s(单位:字节/秒) const throttleStream = new Throttle({ rate: 8 * 1024 * 1024 }) const fileReadStream = fs.createReadStream(path) // 拼接读取流和限速流 const throttledUploadStream = fileReadStream.pipe(throttleStream) // 用putObject传入限速后的流 await minio.putObject('glichester', path.slice(24), throttledUploadStream, metaData) notifier.notify({ title: 'Clip uploaded correctly', message: `Successfully uploaded to the cloud: ${path.slice(24)}`, icon: 'icon.png', sound: true, appID: "Clip saver" }) } catch (err) { notifier.notify({ title: 'Clip upload failed', message: `Failed to upload ${path.slice(24)}... ERROR: ${err}`, icon: 'icon.png', sound: true, appID: "Clip saver" }) } }) })
关键修改点:
- 引入
fs模块创建文件读取流,引入bandwidth-throttle-stream的Throttle创建限速流 - 把
fPutObject替换为putObject,传入拼接后的限速流 - 使用
async/await处理异步上传逻辑,替代回调写法,更易维护 - 用
.once('change')替代.on('change'),避免文件多次变化时重复触发上传
注意事项:
- 先确保安装了依赖:
npm install bandwidth-throttle-stream - 限速速率的单位是字节/秒,所以8MB/s需要换算为
8 * 1024 * 1024字节/秒
内容的提问来源于stack exchange,提问作者Glichester
相关产品推荐
相关产品推荐

