1

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.

3 Answers 3

2

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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?

1 Comment

That should work. I thought there is maybe a better way wo include just the module and the myFuncs.myFuncs1.someFuncs and myFuncs.myFuncs2.someFuncs.
1

From your file index.js on my-jsfunctions, you can export function from other files like so

export * from './functions_1';
export * from './functions_2';

then you can import function

const func1 = require('my-jsfunctions').func1;
const func2 = require('my-jsfunctions').func2;

Comments

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.