30

I want to split the code into different files. I currently write all get and post methods in the same file, but I want greater readability and manageability.

I've tried to put the code in different files, but while running the main app, the rest of get and post methods in other files are not able to called. I include this:

var Db = require('/filename.js'); // ...but I can't call those methods.

I want to split my single file code for readability. How do I achieve this?

EhevuTov
  • 20,205
  • 16
  • 66
  • 71
Raj
  • 837
  • 4
  • 15
  • 24
  • 1
    That's quite [simple](http://nodejs.org/api/modules.html). – Aleksei Zabrodskii Dec 22 '12 at 10:35
  • @elmigranto May I ask you why you answer questions in the comments? I see this very often, but I think Stackoverflow does not want this: http://stackoverflow.com/privileges/comment. Sorry, I'm just curious for the reasons. – Sebastian vom Meer Dec 22 '12 at 14:45
  • @SebastianG Because I'm not answering, but commenting :) Don't think that link or asking for more precise definition or brief statement on topic deserves separate answer (even if combined). I do answer from time to time when I feel like writing sample code and/or searching and providing some links very relevant to the question. – Aleksei Zabrodskii Dec 22 '12 at 16:06
  • I think you (like me) are looking for a sort of PHP's `require` to just append code to your main js file. Have a look at many answers here [https://stackoverflow.com/a/28066576/382515](https://stackoverflow.com/a/28066576/382515) – Ivan Ferrer Villa Oct 08 '17 at 22:49

2 Answers2

21

Just have a look at the module documentation:

Starting with / looks for absolute paths, eg:

require('/home/user/module.js');

./ starts with the path where the calling file is located.

require('./lib/module.js');

__dirname has the same effect than ./:

require( __dirname + '/module.js');
Sebastian vom Meer
  • 5,005
  • 2
  • 28
  • 36
9

Try:

var Db = require('./filename.js');

or

var Db = require('filename.js');

Also, have a look at this blog post.

Ofiris
  • 6,047
  • 6
  • 35
  • 58