I would like to parse a pdf file uploaded on the frontend with a serverless function.
It works locally with a nextjs api route and multer. But will it work in production? Multer basically copies the file on the server and then allows the node script to access it. Even if I delete it just after the parsing operation with fs.unlinkSync()
, I'm not sure that it will work with Netlify or Vercel's serverless functions.
my code is:
import { NextApiRequest, NextApiResponse } from "next";
import nc from "next-connect";
import multer from "multer";
import path from "path";
import pdfParser from "pdf-parse";
import fs from "fs";
export const config = {
api: {
bodyParser: false,
},
};
const handler = nc({
onError: (err: Error, _: NextApiRequest, res: NextApiResponse) => {
console.error(err);
res.status(500).end("bad time");
},
onNoMatch: (_: NextApiRequest, res: NextApiResponse) => {
res.status(404).end("page not found");
},
});
const storage = multer.diskStorage({
destination: (
_,
__,
cb: (error: Error | null, destination: string) => void
) => cb(null, path.join(process.cwd(), "public", "uploads")),
filename: (
_,
file: Express.Multer.File,
cb: (error: Error | null, filename: string) => void
) => cb(null, file.originalname),
});
const upload = multer({ storage });
const uploadFile = upload.single("pdfFile");
handler.use(uploadFile);
handler.post(async (req: any, res: NextApiResponse<any>) => {
const pdffile = fs.readFileSync(req.file.path);
const pdfData = await pdfParser(pdffile, { version: "v2.0.550" });
fs.unlinkSync(req.file.path);
res.status(200).json({ data: pdfData });
});
export default handler;
Could anyone confirm to me that it will work? Or is it necessary that I pay for a dedicated server too? It would be a bummer because it's only for a 20 lines nodejs script.