Gau*_*han 14 node.js coffeescript
我正在使用上传文件Request.
req = request.post url: "http://foo.com", body: fileAsBuffer, (err, res, body) ->
console.log "Uploaded!"
Run Code Online (Sandbox Code Playgroud)
我如何知道实际上传了多少数据?是否有一些我可以订阅的事件或者我可以查询的属性request?
如果没有,那么上传数据并知道上传了多少内容的最佳方法是什么?
我需要处理我的另一个项目的上传进度.
我发现的是,你可以查询request的connection._bytesDispatched属性.
例如:
r = request.post url: "http://foo.com", body: fileAsBuffer
setInterval (-> console.log "Uploaded: #{r.req.connection._bytesDispatched}"), 250
Run Code Online (Sandbox Code Playgroud)
注意:如果您要管道r,请进行轮询r.req.connection.socket._bytesDispatched.
我花了几个小时找到任何有效的request和node来源,最后找到了一种不同的方法,这对我来说更合适.
我们可以依靠drain事件和bytesWritten财产:
request.put({
url: 'https://example.org/api/upload',
body: fs.createReadStream(path)
}).on('drain', () => {
console.log(req.req.connection.bytesWritten);
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要处理文件字节的进度,则更容易使用流data事件:
let size = fs.lstatSync(path).size;
let bytes = 0;
request.put({
url: 'https://example.org/api/upload',
body: fs.createReadStream(path).on('data', (chunk) => {
console.log(bytes += chunk.length, size);
})
});
Run Code Online (Sandbox Code Playgroud)
流缓冲区大小是65536字节,读取/排出过程迭代运行.
这似乎与合作得很好,我node v4.5.0和request v2.74.0.
| 归档时间: |
|
| 查看次数: |
7644 次 |
| 最近记录: |