Skip to content
Advertisement

Node.js https server doesn’t work when I separate it in two files

I have this node.js https server that works when it is in one app.js file but when I split it in 2 files it doesn’t work anymore. I don’t know why..

This app.js works

const https = require('https')
const express = require('express')

const app = express()

const server = https.createServer({
    cert: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/cert.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/privkey.pem'),
}, app)

server.listen(443)

But when I separate it in 2 files app.js and certificate.js it doesn’t work anymore

app.js

const https = require('https')
const express = require('express')
const certificate = require('./certificate.js')

const app = express()

const server = https.createServer({
    certificate.cert,
    certificate.key,
}, app)

server.listen(443)

certificate.js

const fs = require('fs')

var certificate = {
    cert: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/cert.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/privkey.pem'),
}

exports.certificate = certificate

I’m getting this syntax error

certificate.cert
           ^
SyntaxError: Unexpected token '.'

I also tried to to this

const server = https.createServer(certificate, app)

And I was getting this error

connection failed: Error in connection establishment: net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH

So when it was all in app.js file it worked perfectly. But when I tried to separate it in 2 files it doesn’t work anymore..

Advertisement

Answer

It’s a JS syntax error, it has nothing to do with your app being split in two files.

This object is invalid :

{
    certificate.cert, // SyntaxError: Unexpected token '.'
    certificate.key,  //SyntaxError: Unexpected token '.'
}

Try this :

https.createServer({
    cert : certificate.cert,
    key : certificate.key,
})

EDIT : including @StephaneVanraes comments :

You are also importing the certificate wrong, try const { certificate } = require('./certificate.js')

Also, since the property names are the same in both cases you could use the spread operator here: https.createServer({ ...certificate })

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement