Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics Getting Started with Express Creating a Server in Express

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

express()

So, is express is requiring an express class? what actually is happening when we type

const app = express();

it is like we are calling the file we just received as a module.

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Hey Caleb Kemp, sorry for calling you out again, actually I searched it a lot, but couldn't find anything well explained. If by any chance you are online, would you mind helping me out please

1 Answer

Caleb Kemp
Caleb Kemp
12,754 Points

When you require a module require('some_module'); it will search for the specified file, and make the exports object from that file available to your program. For example, just say in the file square.js, there was this code inside

exports.area = function(width) { return width * width; };
exports.perimeter = function(width) { return 4 * width; };

So if I were to write

const mySquare = require('./square');

it would let me directly use those functions i.e. writing

console.log(mySquare.area(4));

would print the value 16.

Now that we understand how modules work, why do I have to use 2 declarations for my Express app, like so?

const express = require('express');
const app = express();

Well, when you require express, it returns the function "createApplication", you can see that if you go to line 28 here. You now have the function in your program, but in order to create the app, the function has to actually run. Therefore it is standard practice to do this in two lines, the require line loads the function, and the second line will run the function. However, it does not have to be written this way, for instance, combining both lines into one like this will also work

const app = require('express')();

However, I recommend sticking to the accepted convention of creating the app in 2 lines, even if it isn't strictly necessary. Hope that helps :smile: