How can you determine the current working directory of a Node.js process and how might this differ between development and production environments?

Node.js interview question for Advanced practice.

Answer

Use process.cwd(); its value depends on the directory from which the Node.js process was launched.

Explanation

process.cwd() returns the directory from which the node command was run, not necessarily where the script file is located. This can differ between environments. In development, you might run node src/app.js from the project root, so cwd is the root. In a production Docker container, the working directory might be set to /app with the WORKDIR instruction.

Related Questions