Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a single Node.js file into separate modules

Tags:

node.js

npm

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?

like image 646
Raj Avatar asked Dec 22 '12 07:12

Raj


People also ask

Why do you need separate modules in node JS?

Each module in Node. js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate . js file under a separate folder.

How do I copy files from one node js file to another?

copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.


1 Answers

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'); 
like image 87
Sebastian vom Meer Avatar answered Oct 08 '22 16:10

Sebastian vom Meer