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 trialkaran Badhwar
Web Development Techdegree Graduate 18,135 Pointsexpress()
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.
1 Answer
Caleb Kemp
12,755 PointsWhen 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
karan Badhwar
Web Development Techdegree Graduate 18,135 PointsThankyou Caleb Kemp, I really appreciate, It means a lot, now I do not get that frustrated, mostly because of your help
Caleb Kemp
12,755 PointsI'm very glad to hear that
karan Badhwar
Web Development Techdegree Graduate 18,135 Pointskaran Badhwar
Web Development Techdegree Graduate 18,135 PointsHey 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