1

I was going through an article on web when I stumbled upon the following code snippet.

I this author have used babel to use ES6 syntax in node and have configured our app in two parts

  1. App.js
  2. Server.js

Inside our Server.js he have done something like this

import express from 'express';
import cors from 'cors';

const app = express();

function setPort(port = 5000) {
 app.set('port', parseInt(port, 10));
}

function listen() {
 const port = app.get('port') || 5000;
 app.listen(port, () => {
   console.log(`The server is running and listening at http://localhost:${port}`);
 });
}

app.use(cors({
 origin: '*', // Be sure to switch to your production domain
 optionsSuccessStatus: 200
}));

// Endpoint to check if the API is running
app.get('/api/status', (req, res) => {
 res.send({ status: 'ok' });
});

export default {
 getApp: () => app,
 setPort,
 listen
};

Here this statement doesn't make sense to me

   export default {
     getApp: () => app,
     setPort,
     listen
    };

And then in app.js, He have done this

import server from './server';

server.listen();

export default server;

Question: Can someone please explain me in stretch what is happening here? Like why is our getApp: () => app written like this and why setPort and listen written normally?

Ps: I know what does export default mean

2 Answers 2

2

The author is exporting an object with three properties as the default export.

Property 1: getApp - This property has a value which is a function that returns the app variable from the server.js file, which is just the express instance. In other words, it is a method which returns the express app.

Property 2: setPort - This property has a value equal to the setPort function defined in the server.js file

Property 3: listen - This property has a value equal to the listen function defined in the server.js file

So when the author calls server.listen() in the app.js file, he/she is just calling the listen function which he/she has imported from the server.js file. Not exactly sure why they've chosen to set the app this way...

Sign up to request clarification or add additional context in comments.

Comments

2

Well, put simply it's an inline function definition utilising ES6 arrow functions syntax which returns the internal app instance.

It's no different to:

getApp: function() {
  return app;
}

The reason it's declared inline is because you don't actually have a function definition anywhere else in the module. If you added the function beforehand then it could be exported the same way as listen / setPort

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.