javascriptnode.jsenvironment-variables

Why NODE_DEBUG=fs environment variable is set but not working?


Node.js docs about a fs module says (https://nodejs.org/api/fs.html#fs_file_system):

To get a trace to the original call site, set the NODE_DEBUG environment variable:

And an example of setting an fs env variable:

$ env NODE_DEBUG=fs node script.js
fs.js:66
    throw err;
          ^
Error: EISDIR, read
at rethrow (fs.js:61:21)
at maybeCallback (fs.js:79:42)
at Object.fs.readFile (fs.js:153:18)
at bad (/path/to/script.js:2:17)
at Object.<anonymous> (/path/to/script.js:5:1)
<etc.>

However, if I set fs env variable upfront in command line or using process.env in the script, the variable is set but doesn't work, no trace is shown:

Upfront in command line:

$ env NODE_DEBUG=fs // set before running a script
$ node script.js // doesn't bring the trace

In the script:

'use strict';
process.env.NODE_DEBUG = 'fs'; // set it on the second line of a script

<...> // script goes here

I both cases the result is as follows, no trace, though NODE_DEBUG=fs is set:

fs.js:81
      throw err;  // Forgot a callback but don't know where? Use NODE_DEBUG=fs
        ^
Error: EISDIR, read
    at Error (native)

The question is. Why command line inline variable setting works:

$ env NODE_DEBUG=fs node script.js,

but other ways of setting it do not work?


Solution

  • env runs a program with a particular environment. If it isn’t passed one, it lists environment variables instead; it can’t modify its parent process’s enivronment. To set an environment variable for the current session, use export:

    export NODE_DEBUG=fs
    node script.js
    

    You can also specify one-off environment variables for a process inline as a shell feature without env:

    NODE_DEBUG=fs node script.js