javascript - node.js how to stop a running api -


i created script read growing file using "tailstream", working fine , code below.

var http = require('http'); var tailstream = require('tailstream');  http.createserver(function(req, res) {   var filename = "d:\\test.txt";   var readstream = tailstream.createreadstream(filename);   readstream.on('open', function () {         readstream.pipe(res);   });   readstream.on('error', function(err) {     res.end(err);   });    settimeout(function () {             console.log('timeout completed');              readstream.done();         }, 10000);     //readstream.done();  }).listen(8080); 

it working absolutely fine , stops reading after 10 seconds mentioned in settimeout. want stopped button click on ui. possible pass signal ui , stop streaming ? suggestion great help.

many in advance.

here solution, code not tested (not sure tailstream is).

you should implement 2 functions client (browser, ui), both of them have "jobid" query string parameter:

function "/tail?jobid=1" starts readstream , cache global variable, "jobid" used index readstream each request, because each request creates readstream object, must make "jobid" unique (timestamp or uuid) each request "/tail". pair call "/stop?jobid=1" search given id , fetch associate readstream stop it:

const http = require('http'); const url = require('url'); const tailstream = require('tailstream');  var jobs = new map();  http.createserver(function (req, res) {     let parsedurl = url.parse(req.url, true);      if (parsedurl.pathname === '/tail') { // send stream data         var filename = "d:\\test.txt";         var readstream = tailstream.createreadstream(filename);         readstream.on('open', function () {             readstream.pipe(res);         });         readstream.on('error', function (err) {             res.end(err);         });          jobs.set(parsedurl.jobid, readstream);      } else if (parsedurl.pathname === '/stop') { // stop job         var readstream = jobs.get(parsedurl.jobid);         if(readstream) {             readstream.done();         }         res.end();     }  }).listen(8080); 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -