I'm trying to put JSON data in a blob and then upload it as a .json file into my cloud storage.
I have initialized the storage as var storage = admin.storage() in earlier code, my function is trying to get date which is then formatted to reflect name of the JSON object from previous day, retrieves it from realtime DB and then stringifies it, everything works to this point as I've been logging data along the way, however once I try to upload the blob I'm getting below error:
Error: Process exited with code 16 at process.on.code (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:396:29) at process.emit (events.js:198:13) at process.EventEmitter.emit (domain.js:448:20) at process.exit (internal/process/per_thread.js:168:15) at logAndSendError (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:184:9) at process.on.err (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:389:13) at process.emit (events.js:203:15) at process.EventEmitter.emit (domain.js:448:20) at process._fatalException (internal/bootstrap/node.js:497:27)
Here is my code:
exports.archiveLogs = functions.pubsub
.schedule("every day 01:01")
.onRun((context) => {
//get previous date in correct format (to reference collection name)
var rightNow = new Date();
var dateOffset = 24 * 60 * 60 * 1000 * 1; //1 days
rightNow.setTime(rightNow.getTime() - dateOffset);
//to formatted string
var day = rightNow.toISOString().slice(0, 10).replace(/-/g, "");
console.log("Running archive logs with date: ", day);
var ref = logDB.ref(`logs/${day}`);
//retrieve data from realtime db
ref.on(
"value",
function (snapshot) {
//stringy retrieved data and put it in a blob
var dataString = JSON.stringify(snapshot.val());
var blob = new Blob([dataString], {
type: "application/json",
});
//reference to location where the file will be saved
var storageRef = storage.ref().child(`/logs/${day}.json`);
storageRef
.put(blob)
.then((snapshot) => {
console.log("Uploaded a blob!");
logUserActivity(
"system",
"system",
"archive_logs",
"Pass",
`Created JSON: ${day}.json at /logs/`
);
return true;
})
.catch((err) => {
console.log("Error uploading to storage.", err);
});
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
}
);
});