'File System can be used in firebase cloud functions in my case
I created a pdf to zpl converter for a recent local project, everything works perfectly,but the project to host it use firebase functions to deploy.
-Project Structure-
- index.js(file)
- controller(directory)=> convertorController.js
- routes(directory)=> converterRoutes.js
- processFile(directory where locally I save temporally files)
index.js
const functions = require("firebase-functions");
const express = require('express')
const app = express();
const port = 8080;
//Api Route
const convertorRoutes = require('./routes/convertorRoutes');
app.use('/convert-pdf-to-zpl',convertorRoutes);
........
exports.zlp_ip = functions.https.onRequest(app)
routes/converterRoutes.js
const express = require('express');
const convertorController = require('../controller/convertorController');
const router = express.Router();
router.route('/:width/:height').post(
convertorController.conversion1,
convertorController.conversion2,
convertorController.conversion3
)
module.exports = router;
controller/convertorController.js
//Native Node Js Module
const https = require('https');
const fs = require('fs');
.................
const resizeImg = require('resize-img');
//Create PDF
exports.conversion1=(req,res,next)=>{
try {
if(fs.existsSync(pdfPath)){
return next()
}else{
//Get Global Url
let urlPdf = req.body.url_pdf;
//Save pdf locally
https.get(urlPdf, function(response) {
//Save file loccly
const file = fs.createWriteStream("./processFile/file.pdf");
response.pipe(file);
//If is onfinish start png conversion
file.on('finish',function(){
file.close();
return next()
})
});
}
} catch(err) {
res.status(403).json({
status:'failed to extract pdf',
messahe:err
})
}
}
The other functions convert pdf to base64 and then to the desired format all temporary files being saved in processFile,when I uploaded the project to firebase and tested it, it gave me the following error in the postman << Error: could not handle the request/500Internal Server Error>>,after searching the internet I discovered that cloud functions work differently, they have a / tmp default.
I found an adaptation using .
const os = require('os');
let tmpDir = os.tmpdir();
and then I replaced the code path with my files
const pathPdf = tmpDir+'/file.pdf'
const file = fs.createWriteStream(tmpDir+"/file.pdf");
the first function is running, the file is saved without any problems, but when I try to access it in the next one to convert to png, it can't find it anymore. In total I have to save 3 files that I delete when the conversions are completed, but I can't understand how this cloud functions storage works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
