Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question