Stream 如何在hapijs中通过管道将exceljs流发送到应答
我正在使用exceljs生成一个excel文件(使用它的流功能)。我不想将文件保存在服务器上,然后读取并返回它,而是直接将exceljs流传输到hapijs中的响应Stream 如何在hapijs中通过管道将exceljs流发送到应答,stream,streaming,hapijs,exceljs,Stream,Streaming,Hapijs,Exceljs,我正在使用exceljs生成一个excel文件(使用它的流功能)。我不想将文件保存在服务器上,然后读取并返回它,而是直接将exceljs流传输到hapijs中的响应 function(request, reply) { const options = { stream: reply, // I need to somehow declare the reply stream here useStyles: false, useSharedStrings: true
function(request, reply) {
const options = {
stream: reply, // I need to somehow declare the reply stream here
useStyles: false,
useSharedStrings: true
};
const workbook = new Excel.stream.xlsx.WorkbookWriter(options);
workbook.addWorksheet('Test');
const worksheet = workbook.getWorksheet('Test');
worksheet.columns = [{
header: 'product', key: 'product'
}];
worksheet.addRow({product: 'MyProduct'}).commit();
worksheet.commit();
workbook.commit();
这可能吗?我不能像在expressjs中那样直接将reply传递给Exceljs流的选项?有什么想法吗?Reply可以返回流,但我会将exceljs逻辑封装在您自己的流接口中,您可以将其传递到hapi的Reply接口,我使用该模块实现了这一点。查看模块以展示如何包装流,在我的示例中,它仅从excel转换为jsonCode,不鼓励使用“尝试此”答案。请解释这为什么以及如何解决op的问题。你可以阅读exceljs图书馆网站上的Streaming XLSX部分,它在那里解释了如果我之前的评论被认为是粗鲁的话会带来的使用问题。尽管你可能仍然想加入额外的信息来提高你答案的长期价值。“始终引用重要链接的最相关部分,以防目标站点无法访问或永久脱机”-。-虽然没有给出示例,但说明如下:如果选项中既没有指定流也没有指定文件名,工作簿编写器将创建一个StreamBuf对象,该对象将XLSX工作簿的内容存储在内存中。此StreamBuf对象可通过属性workbook.stream进行访问,可用于通过stream.read()直接访问字节,或通过管道将内容传输到另一个流。”
var wb = new Excel.stream.xlsx.WorkbookWriter();
var sh = wb.addWorksheet('sheet1');
sh.columns = [
{ header: 'Name', key: 'name' },
{ header: 'Age', key: 'age' }
];
sh.addRow(['Ben', 8]);
sh.addRow(['Dave', 10]);
sh.commit();
wb.commit()
.then(function () {
var stream = wb.stream;
var b = stream.read();
reply(b)
.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
.header('Content-Disposition', 'attachment; filename=file.xlsx')
.header('Content-Length', stream.length);
});