Can you use fs (writeFile) and exec with Google App Engine?

Issue

I created an express server, which also writes some text into a file I have in the project directory and executes a cmd command. Locally, it works, but if I deploy it to App Engine and try to make a request I get error 500.

If there isn’t a way to do this, what could I do instead of it? I guess for fs, storing it in Cloud Storage, but I don’t know about exec-

The code:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { exec } = require('child_process');
var fs = require('fs')


const app = express();
app.use(bodyParser.json());
app.use(cors());
module.exports = app

app.post("/", (req,res) =>{ 
    console.log("Get from /"); 
    console.log(req.body.data)
  
  
    fs.writeFileSync('../log.txt', req.body.data);

    exec('npx hardhat run scripts/deploy.js --network goerli',
        (error, stdout, stderr) => {
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
            else{
              var addr = fs.readFileSync('../address.txt','utf8')
              res.send(addr);
            }
        })
  res.send(req.body.data);
                            });

// starting the server
app.listen(8080, () => {
  console.log('listening on port 8080');
});

Solution

For App Engine Standard, you can’t write to the local file system. You can write to /tmp which is a temporary directory. All files in this directory are stored in your instance’s RAM which means you lose the file when the instance goes down (see documentation)

For App Engine Flexible, you can write to local disk but the disk is re-initialized whenever the VM is (re)started (see documentation)

Best thing would be to write to cloud storage

Answered By – NoCommandLine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published