2

I'm new to Node/Express and I'm not entirely sure where things go...

I want to have a little custom class - where do I put this custom code in my express app? I seem to have to put it inside "node_modules" for it to be picked up by require which isn't really what I want. Ideally I'd like to have it in a lib folder or the likes.

How can I do this?

1 Answer 1

1

Let's say you had a Person class like this in lib/person:

var Person = function (firstName) {
  this.firstName = firstName;
};

You can export this using node's module.exports like this (in lib/person):

module.exports = Person;

To use the person class you would then do:

var Person = require('./lib/person');   
var jim = new Person('jim');
Sign up to request clarification or add additional context in comments.

2 Comments

Hey! Thanks for answering. I tried this... is it still './lib/person' if you are calling require from /routes/index.js? It can't seem to find it.
That's it, glad I could help!

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.