Can you return a file buffer a route handler?
Answered
Thai posted this in #help-forum
ThaiOP
Is it possible to return a file in a route.ts? For example I am using
easy-template-x to create a document and would like to return it in a route, if this isn't possible I can come up with another solution export const dynamic = 'force-dynamic' // defaults to auto
import * as fs from 'fs';
import { TemplateHandler } from 'easy-template-x';
export async function GET(request: Request) {
const templateFile = fs.readFileSync('my-template.docx');
const data = {
FirstName: 'Bob',
LastName: 'Jones',
};
const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);
fs.writeFileSync('myTemplate - output.docx', doc);
return Response.json({ hello: 'world' }) // Return here
}Answered by Ray
yes, try this
import fs from "fs";
import { TemplateHandler } from "easy-template-x";
export async function GET(request: Request) {
const templateFile = await fs.promises.readFile("my-template.docx");
const data = {
FirstName: "Bob",
LastName: "Jones",
};
const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);
await fs.promises.writeFile("myTemplate - output.docx", doc);
return new Response(doc, {
headers: {
"Content-disposition": "attachment; filename=myTemplate - output.docx",
},
});
}2 Replies
@Thai Is it possible to return a file in a route.ts? For example I am using `easy-template-x` to create a document and would like to return it in a route, if this isn't possible I can come up with another solution
js
export const dynamic = 'force-dynamic' // defaults to auto
import * as fs from 'fs';
import { TemplateHandler } from 'easy-template-x';
export async function GET(request: Request) {
const templateFile = fs.readFileSync('my-template.docx');
const data = {
FirstName: 'Bob',
LastName: 'Jones',
};
const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);
fs.writeFileSync('myTemplate - output.docx', doc);
return Response.json({ hello: 'world' }) // Return here
}
yes, try this
import fs from "fs";
import { TemplateHandler } from "easy-template-x";
export async function GET(request: Request) {
const templateFile = await fs.promises.readFile("my-template.docx");
const data = {
FirstName: "Bob",
LastName: "Jones",
};
const handler = new TemplateHandler();
const doc = await handler.process(templateFile, data);
await fs.promises.writeFile("myTemplate - output.docx", doc);
return new Response(doc, {
headers: {
"Content-disposition": "attachment; filename=myTemplate - output.docx",
},
});
}Answer
ThaiOP
awesome