Sending stream from controller #131
-
Hi @neonexus, Could you please show me an example for sending a stream (due to the file size) from Sails controller to front-end in a proper way as we have custom responses? For example, I need to send a PDF file read from disk to the front-end for displaying it in an iframe. Thank you. const fs = require('fs');
const path = require('path');
module.exports = {
friendlyName: 'Send PDF',
description: 'Read a PDF from disk and send its content.',
inputs: {
filePath: {
type: 'string',
description: 'Path to the PDF file on disk.',
required: true
}
},
exits: {
success: {
responseType: 'ok'
},
notFound: {
responseType: 'notFound'
},
serverError: {
responseType: 'serverError'
}
},
fn: async function (inputs, exits) {
try {
const filePath = inputs.filePath;
// Check if the file exists
if (!fs.existsSync(filePath)) {
return exits.notFound(`File not found at ${filePath}`);
}
// Get the file name from the file path
const fileName = path.basename(filePath);
// Set the appropriate headers for the PDF response
this.res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': `inline; filename="${fileName}"`
});
// Create a readable stream from the PDF file
const stream = fs.createReadStream(filePath);
// Pipe the stream to the response object
stream.pipe(this.res);
// Handle the end of the stream
stream.on('end', () => {
return exits.success();
});
// Handle any errors that occur during streaming
stream.on('error', (error) => {
return exits.serverError(error.message);
});
} catch (error) {
// Handle any other errors
return exits.serverError(error.message);
}
}
}; is the above code optimal or any better to send such data from controller? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
@neonexus, |
Beta Was this translation helpful? Give feedback.
-
Did you get this fixed @MaheshkumarSundaram ? Also, I just pushed a new release. It has an update to the request logger I meant to put out a long time ago; something I'm sure you'll appreciate if you are still using the logger: v5.3.2...v5.3.3 |
Beta Was this translation helpful? Give feedback.
You can’t use old style ‘this.res’, you have to use the third parameter ‘env’.
See the login controller I believe for an example.