'how to send readstream as response
when i try to send read stream as response i am getting error
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
response.send(readStream)
})
.listen(2000);
i want to send as response.send(readStream) not as readStream.pipe(response); is there is any possibility to send like this ?
Solution 1:[1]
The HTTP response object in node (response
in the code above) is a writable stream. This means if we have a readable stream that represents the content of myfile.mp3
, you can just pipe the content of the file into the response object. This would look something like this:
readStream.pipe(response)
This prevents the file (i.e. myfile.mp3
) being loaded completely into memory before sending it as a response, and is the suggested way to do so in order to prevent high memory pressure on the server side.
Is there any possibility to send files without using pipe()
?
Actually there is a method which allows to send files without using pipe()
, but this approach is discouraged as it first loads the whole file into memory and after that writes the file to the response object. Anyways, here is an example on how to do it:
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
fs.readFile(filePath, (err, data) => {
if (err) throw err;
response.end(data);
});
}).listen(2000);
Solution 2:[2]
If that is what you really want, then you could do it like this:
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var readStream = fileSystem.createReadStream(filePath);
response.writeHead(200, { 'Content-Type': 'audio/mpeg' });
readStream.on('data', data => response.send(data));
readStream.on('close', () => response.end());
})
.listen(2000);
Otherwise readStream.pipe(response):
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var readStream = fileSystem.createReadStream(filePath);
response.setHeader('Content-Type', 'audio/mpeg');
readStream.pipe(response);
})
.listen(2000);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bajro |
Solution 2 |