Warm tip: This article is reproduced from serverfault.com, please click

How can my script read the updated value of an environment variable (updated by another process)?

发布于 2020-11-27 18:09:16

I have the following node script that waits for an environment variable to change value:

// wait-for-url.js
(async function () {
    console.log('Waiting for a complete URL...');

    while (true) {
        const url = process.env.URL;
        const isUrlIncomplete = url.includes('..creating..');

        if (isUrlIncomplete) {
            console.log(
                `URL is still being provisioned (${url}). Trying again in 1 minute.`,
            );

            await sleep(60000);
        } else {
            console.log('URL is fully provioned!');
            break;
        }
    }
})();

function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

The environment variable URL is being updated by another process, so it seems like my node script can never access the new value of process.env.URL.

How can my script read the the new value of an environment variable that was set by another process which I don't control?

Really what I want to do is wait for the URL env variable to be set and follow it with running tests once it is:

node scripts/wait-for-url.js && npm run test

If there is no possible way to access the new env variable from inside my node script, is there a way I can at least modify my command line to achieve the same result?

Questioner
maximedupre
Viewed
0
Kurtis Rader 2020-11-29 02:41:03

The environment variable URL is being updated by another process, so it seems like my node script can never access the new value of process.env.URL.

That is correct. Environment variables are private to each process; not global. A process can only directly modify its env vars. It also has control over the env vars of any process it starts. But it cannot directly modify the env vars of a different process. You're trying to use env vars in a fashion they weren't designed to accommodate.

You'll have to use some form of IPC to communicate the changed env var from process A to process B.