Summer Sale! All accounts are 50% off this week.

martinszeltins's avatar

How to separate Node.js app into 2 different files?

I have a simple Node.js app. But I would like to extract one part of it into another file but I don't know how to do this.

Here is my app

const fs = require('fs')
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)

I would like to put this part into a file certificate.js and include it in my main app.js file

certificate.js

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)

I would appreciate some help on this...

0 likes
1 reply
rodrigo.pedra's avatar

I assume you have more on your file so you want to separate it, as it is the code you want to move needs all the other requires as dependencies in order to work.

If you only want the certificate parts in other file you could try this:

// certificate.js
const fs = require('fs');

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

module.exports = certificates;

And in your app.js file:

// app.js
const https = require('https');
const express = require('express');
const certificates = require('./certificates.js');

const app = express();
const server = https.createServer(certificates, app);

server.listen(443);

other option

To separate everything you asked in the OP, you would need to move almost everything, which I don't see the reason, but if you want it anyway you could try this:

// certificate.js
const fs = require('fs');
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);

module.exports = server;

See that as the code has almost all the dependencies we moved most of it to the new file.

// app.js
const server = require('./certificates.js');

server.listen(443);

Please or to participate in this conversation.