Search code examples
javascriptfirebaseapiexpressbusboy

Uploading documents, pdf's to google cloud using firebase. Get error


I'm trying to upload simple documents using busboy / express.js to google cloud.

I am getting this error.

Error: Cannot find module 'busboy/lib/types/node_modules/dicer'

and this is the code for the request.

// Upload a document for claim
exports.uploadDocument = (req, res) => {
  const BusBoy = require("busboy");

  const path = require("path");

  const os = require("os");

  const fs = require("fs");

  const busboy = new BusBoy({ headers: req.headers });

  let DocumentToBeUploaded = {};
  let DocumentFileName;
  // change this section to storing pdfs and docs etc

  busboy.on("file", (fieldname, file, filename) => {
    console.log(fieldname, file, filename);

    const documentExtension = filename.split(".")[
      filename.split(".").length - 1
    ];
    // 32756238461724837.png
    DocumentFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${documentExtension}`;
    const filepath = path.join(os.tmpdir(), DocumentFileName);
    DocumentToBeUploaded = { filepath, mimetype };
    file.pipe(fs.createWriteStream(filepath));
  });
  busboy.on("finish", () => {
    admin
      .storage()
      .bucket()
      .upload(DocumentToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: DocumentToBeUploaded
          }
        }
      })
      .then(() => {
        const docUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${DocumentFileName}?alt=media`;
        return db.doc(`/users/${req.Claim.ClaimId}`).update({ docUrl });
      })
      .then(() => {
        return res.json({ message: "document uploaded successfully" });
      })
      .catch(err => {
        console.error(err);
        return res.status(500).json({ error: "something went wrong" });
      });
  });
  busboy.end(req.rawBody);
};

Just trying to upload a very simple text document currently. Surely it can't be that difficult and I'm making a simple mistake somewhere.

Appreciate the help :)


Solution

  • You need to install busyboy:

    npm i busboy
    

    You can find more about this npm package in the following link:

    https://www.npmjs.com/package/busboy