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

Node.js express modules - requiring modules from app.js

I'm having a hard time splitting out my node.js app using express. Here's my structure

     app.js
     node_modules
     package.json
     routes
       -> index.js
       -> anotherfile.js
       -> yetanotherfile.js
  1. so app.js requires ./routes
  2. the index.js of ./routes requires anotherfile.js & yetanotherfile.js

This is all well and good, but how do I access node_modules I've declared in app.js?

For example, I have declared this module in app.js var shopifyAPI = require('shopify-node-api'); But I want to use it down in anotherfile.js

How do I do this?

Many thanks

1 Answer

You need to require it in each node file that you want to use it in. This is how the express generator sets it up:

app.js:

var express = require('express');
var routes = require('./routes/index');

index.js:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

express is essentially a local variable in both files. You can access the router variable from index.js in app.js thanks to the module.exports = router line. In your instance, you need to have var shopifyAPI = require('shopify-node-api') in anotherfile.js and make sure you use module.exports = exportedStuff to give your other files access to whatever this file does within the module.