How to stop loading and redirecting in busboy if the mime type is not valid?

I am new to Node.js and I use Express and Busboy-Connect to create a simple file upload form, only for wav files. Here's what I'm trying to do: - start the download - if the mimetype type is not wav, redirect to the error page - else: write the file to the server and redirect it back.

If the mimetype type is valid, everything works fine, but if it isn't, I cannot redirect and the browser just hangs and eventually expires. My understanding of this is that the browser does not want to redirect because it is waiting for the download to complete, but how can I cancel the download in my js code? I could get around the problem and write a file and then delete it if it is not the correct mimetype type, but I think it is a bit silly to do this, I would rather find a way to trigger an event that stops it and redirects immediately. Here is (snippet code) of my application code:

app.get('/', function (req, res) { res.render(__dirname + '/public/index.ejs', {error: 0}); }); app.get('/error', function (req, res) { res.render(__dirname + '/public/index.ejs', {error: 1}); }); app.post('/upload', function (req, res) { var timestamp = new Date().getTime().toString(); //console.log(timestamp); var fstream; req.pipe(req.busboy); req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { if ("audio/wav" != mimetype) { console.log("invalid mimetype"); // that prints ok // req.busboy.end(); // I tried that but it doesn't work res.redirect('/error'); } else { console.log("Uploading: " + mimetype); fstream = fs.createWriteStream(__dirname + '/tmp/' + timestamp + filename); file.pipe(fstream); fstream.on('close', function () { res.redirect('back'); }); } }); }); 

Can someone point me in the right direction? Thanks for the help!

+6
source share
1 answer

Well, I found it in npm docs, if you think that anyone may be interested in finding this answer from a google search, you can leave it allowed, otherwise you can close / delete this entry.

Basically, there is a function in the thread that needs to be called to unlock busboy, so all I had to do to get it to work was add

 file.resume(); 

before redirecting to the error page.

+2
source

Source: https://habr.com/ru/post/986360/


All Articles