如何在Node.js服务器中配置根CA证书?ssl-root-cas模块调用报错求助
ssl-root-cas inject() Error on Mac High Sierra (Node.js) Let's break down what's happening here and fix that error step by step.
Why You're Seeing This Error
The inject() method in your version of ssl-root-cas is trying to split a file path string, but it's receiving an undefined or non-string value instead. This usually happens because the module can't automatically locate the default root certificate files on your system—especially since you couldn't install it globally, so local path resolution is misfiring.
Fix 1: Manually Specify the Default Cert Path for inject()
Since automatic path detection is failing, pass the full path to the module's bundled root certificates directly to inject(). Here's how to adjust your code:
First, confirm you have the module installed locally:
npm install ssl-root-cas --save
Then update your JS file:
const fs = require('fs'); const path = require('path'); const sslRootCas = require('ssl-root-cas'); // Get the full path to the bundled root certificates in your local node_modules const defaultCertsPath = path.join(__dirname, 'node_modules', 'ssl-root-cas', 'ca', 'root certificates.crt'); // Inject the default certs first, then add your custom root cert sslRootCas.inject(defaultCertsPath).addFile(conf.root_cert);
This gives inject() a valid file path to work with, so the split() call won't throw an error anymore.
Fix 2: Skip the Module Altogether (Simpler Approach)
If you don't need the full suite of bundled root certificates, you can directly modify Node.js's global HTTPS agent to include your custom CA without relying on ssl-root-cas. This avoids any path resolution issues entirely:
const https = require('https'); const fs = require('fs'); // Read your custom root certificate const customRootCert = fs.readFileSync(conf.root_cert); // Merge your custom cert with Node.js's existing trusted CAs https.globalAgent.options.ca = [ ...(https.globalAgent.options.ca || []), customRootCert ];
This approach keeps things lightweight and avoids module-specific bugs.
Note on Global Installation Failure
If you still want to install ssl-root-cas globally, you likely hit a macOS permission issue. Try installing it with admin privileges:
sudo npm install ssl-root-cas -g
Just remember global npm modules typically require sudo access on Unix-like systems.
内容的提问来源于stack exchange,提问作者satish

