A
A
Alexander2016-04-05 09:23:36
JavaScript
Alexander, 2016-04-05 09:23:36

How to stop writing to stream if a certain file size has been reached?

Good morning everyone!=)
I'm trying to deal with streams in NodeJS, but unfortunately not everything is as simple as we would like. Code first:

'use strict';

let url = require('url');
let fs = require('fs');
let path = require('path');

require('http').createServer(function(req, res) {

  let pathname = decodeURI(url.parse(req.url).pathname);

  switch(req.method) {
  case 'POST' :
    let fileName = path.basename(pathname);
    fs.access('./files/' + fileName, (err) => {
      if(err) {
        let fileSize = 0;
        let stream = fs.createWriteStream('./files/' + fileName);
          req.on('error', (err) => {
            console.log('err');
            res.statusCode = 500;
            res.end();
          });
          req.on('readable', () => {
            let chunk = req.read();
            if(chunk != null) {
              fileSize += chunk.length;
            
              if(fileSize > 1048576) {
                stream.end();
                res.statusCode = 413;
                res.end();
              }
              stream.write(chunk);
            }

          });
          req.on('end', () => {
            stream.end();
            res.statusCode = 200;
            res.end('Ok');
          });
      } else {
        res.statusCode = 409;
        res.end();
      }
    });
    break;
  default:
    res.statusCode = 502;
    res.end("Not implemented");
  }

}).listen(3000);

If the file(request stream) is larger than 1MB, then I try to finish writing to the stream(file) and issue a 413 error code. But everything falls, so I'm doing something wrong.
Tell me what's wrong?)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question