Save file to system during onPreBuild hook

Hi,

This question is more about understanding how the build process works rather than solving a technical issue I’m experiencing.

I’ve defined the following onPreBuild hook and confirmed it runs:

 1 const fs = require('node:fs');
 2 const { Vault } = require('MY_PRIVATE_REPO');
 3
 4 module.exports = {
 5   onPreBuild: async () => {
 6     const MAX_RETRY_ATTEMPTS = 3;
 7     let retryCount = 0;
 8
 9     while (retryCount < MAX_RETRY_ATTEMPTS) {
10       try {
11         //const vault = new Vault(process.env.VAULT_ENV);
12         const vault = new Vault("demo");
13         await vault.authenticate();
14         const envVars = await vault.read('unified');
15         const fileData = JSON.stringify(envVars);
16         if (typeof envVars === 'object') {
17           fs.writeFile('./myfile.txt', fileData, { flag: 'w' }, function(err) {
18               if (err)
19                   return console.error(err);
20               fs.readFile('./myfile.txt', 'utf-8', function (err, data) {
21                   if (err)
22                       return console.error(err);
23                   console.log(data);
24               });
25           });
26
27           return;
28         } else {
29           retryCount++;
30           console.log('Error: ', envVars);
31           console.log('Retrying to fetch Vault variables...');
32         }
33       } catch (error) {
34         console.error('Failed to fetch Vault environment variables:', error);
35         process.exit(1);
36       }
37     }
38
39     console.error('Reached maximum retry attempts. Unable to fetch Vault environment variables.');
40     process.exit(1);
41   },
42 }

When I run netlify build locally, everything runs without error and I see the data that is read from myfile.txt logged to the console, as though the file myfile.txt exists.

However, when the build finishes and I navigate to the location where myfile.txt is supposed to be, I don’t see a file persisted.

So my question: does the netlify build command run in some kind of virtualized environment such that the myfile.txt file is getting created and persisted, just not on my local machine?

CLI is not run in any virtualized environment, but I believe the file might be getting written somewhere you don’t expect. I’d recommend using something like path.join() or process.cwd() to ensure you generate an absolute path to the directory you want to write in.