When I update my node version I find that I need to rebuild the packages that use compiled C++ binaries like bcrypt. I get an error like NODE_MODULE_VERSION mismatch. Other answers correctly state that to fix this I can run the command npm rebuild --build-from-source
. I want to write a script to check if these libraries are in need of an update proactively rather than waiting for my build to fail. How can I check if my version of node is compatible with the current compiled binaries for these packages?
This has to do with node's binary interpreter. According to this node version page
NODE_MODULE_VERSION refers to the ABI (application binary interface) version number of Node.js, used to determine which versions of Node.js compiled C++ add-on binaries can be loaded in to without needing to be re-compiled. It used to be stored as hex value in earlier versions, but is now represented as an integer.
However it takes some digging to find that the current NODE_MODULE_VERSION can be printed like so:
node -p process.versions.modules
Compiled binaries include a config.gypi file which lists the NODE_MODULE_VERSION that the package was compiled against.
Thus in order to check if your binaries are compiled correctly you can run the following script:
VERSION_MISMATCH=$(grep -E "\"node_module_version\": " -r ./node_modules --include "config.gypi" | grep -v "$(node -p process.versions.modules)")
if [ ${#VERSION_MISMATCH} > 0 ]; then
npm rebuild --build-from-source -q
fi
I would recommend listing out all the packages that you'd expect would need rebuilding in the rebuild statement, e.g.
npm rebuild bcrypt ... --build-from-source -q
so that you only rebuild your ABI packages. You also might be able to modify the script above to rebuild only the ABI packages that were found in the grep.