简体   繁体   English

node.js提前终止请求

[英]node.js killing a request early

In my app I'm downloading a file if I click on it thanks to http.get 在我的应用程序中,如果我单击http.get,就可以下载文件

var buffer = fs.createWriteStream('file.txt');
$('a').click(function(){
    http.get(url, function(res) {
        res.on('data', function(chunk) {
             buffer.write(chunk);

and if I click on a second link, it will download it on the same buffer as well. 如果我单击第二个链接,它也会将其下载到相同的缓冲区中。

this doesn't work well and the two files get mixed. 这不能很好地工作,并且两个文件混合在一起。

  • What I want is to kill the first request when I start the second one, any idea how to do this? 我想要的是在启动第二个请求时杀死第一个请求,知道如何执行此操作吗?

  • Also I'm using http.get , but sometimes the module request.get , I don't see any differences, which one should I use for this job? 另外,我使用的是http.get ,但是有时使用request.get模块,我看不到任何区别,我应该使用哪一项来完成这项工作?

I found a way around with event emitters: 我找到了一种方法与事件发射器:

require('event')

just emit something, and catch it to kill the request with a res.destroy(); 只是发出一些东西,并用res.destroy()捕获它以终止请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM