NodeJS module structure for multiple .js files with functions
ATM I have a folder in my NodeJS application where I store my JS files with a couple of functions. I require these files in my main.js at the top an use them as usual.
my-app/
├── node_modules/
├── my_jsfiles/
│ ├── functions_1.js
│ └── functions_2.js
├── package.json
└── main.js
main.js:
const myFuncs1 = require('./my_jsfiles/functions_1.js')
const myFuncs2 = require('./my_jsfiles/functions_2.js')
myFuncs1.someFuncsInside()
myFuncs2.someFuncsInside()
APPROACH: Now that I am going to use my_jsfiles in more applications I would like to make my own NodeJS module, which works so far, but I stuck at the point how I can include multiple js files instead of just calling functions from the index.js
my-app/
├── node_modules/
│ ├── my-jsfunctions/
│ │ ├── index.js
│ │ ├── functions_1.js
│ │ └── functions_2.js
├── package.json
└── main.js
main.js:
const myFuncs = require('my-jsfunctions')
//How do I call functions from functions_1.js and functions_2.js?
I know that I can export functions from the index.js
exports.someFunction = function () {
console.log("This is a message from the index.js");
}
But what is the propper way to call functions from the other files, because I do not want to have just one index.js file with million lines of code.
Solution 1:
you just need to import all your functions into index.js file and export from there
my-app/
├── node_modules/
├── my_jsfiles/
│ ├── functions_1.js
│ └── functions_2.js
├── package.json
└── main.js
function_1.js
function functions_1_1(){
}
module.exports={functions_1_1}
function_2.js
function functions_2_1(){
}
module.exports={functions_2_1}
index.js
const {functions_1_1} = require("./function_1.js");
const {functions_2_1} = require("./function_2.js");
module.exports={functions_1_1,functions_2_1}
main.js
const {functions_1_1,functions_2_1} =require("./my_jsfiles/index.js");
functions_1_1()
functions_2_1()
Solution 2:
you should just be able to do
const myFuncs1 = require('my_jsfiles/functions_1.js')
const myFuncs2 = require('my_jsfiles/functions_2.js')
isn't it working?