Disabling Warnings in Node.js

May 15, 2019

When we ship an application, we wouldn’t ever want our end users to be puzzled by the seemingly random “unstable” or “deprecation” warnings caused by the libraries that we have used to build the app.

Normally in Node.js, we can disable all runtime warnings by setting an environmental variable NODE_NO_WARNINGS=1. If our app is launched via a shell script, we can set this variable with statement export NODE_NO_WARNINGS=1. We can also pass an extra argument to node itself to disable warnings when we start the app interactively: node --no-warnings ./path/to/entrance_script_of_the_app.js.

However, since multiple arguments in the shebang line is generally unsupported, if we want to the entrance script an executable, there’s no good solution to set up the no-warnings option or environmental variable in the beginning of the file. I have recently encountered this problem while working on a Node.js CLI side project - this snippet below won’t work!

#!/usr/bin/env node --no-warnings

// This won't work!!
console.log("Hiya!");

In this case, we can instead use a launcher script to spawn a child_process as a workaround. Ugly, and we can’t really do any debugging this way, but it works with npm link and global installs -

#!/usr/bin/env node
const { spawnSync } = require("child_process");
const { resolve } = require("path");

// Say our "real" entrance script is `app.js`
const cmd = "node --no-warnings " + resolve(__dirname, "app.js");
spawnSync(cmd, { stdio: "inherit", shell: true });

If you only wanted to disable the warnings because you used the fs.promises API as I did, I would recommend you to wrap the original APIs in a promise manually next time to avoid the hassle, or simply sticking to util.promisify as well as the sync version of the APIs, instead of using this workaround.