对于 node 0.3.4及更高版本,直到当前LTS(本次编辑时为v16),https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener具有您需要的所有示例代码:
const https = require(`https`);
const fs = require(`fs`);
const options = {
key: fs.readFileSync(`test/fixtures/keys/agent2-key.pem`),
cert: fs.readFileSync(`test/fixtures/keys/agent2-cert.pem`)
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end(`hello world\n`);
}).listen(8000);
请注意,如果要使用Let's Encrypt’s certificates using the certbot tool,则私钥名为privkey.pem
,证书名为fullchain.pem
:
const certDir = `/etc/letsencrypt/live`;
const domain = `YourDomainName`;
const options = {
key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
};