-1

This is kind of a silly question, but I want to be able to write code in different files, and then import the code and use it all, like have it written in different files and it all work together.

like this:

routes
   login.js
   register.js

views
   index.ejs
   login.ejs
   register.ejs

app.js

so if I create a function inside register.js, how do I say, hey, call that function in login.js now, and have it work? do I have to import the files all in app.js? I have only done small projects where this hasn't been necessary, but now I need to :)

Thanks for the help

Gianluca
  • 900
  • 8
  • 27
  • Try searching for "node require function" – Cully Mar 15 '21 at 04:27
  • 1
    Does this answer your question? [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – Cully Mar 15 '21 at 04:27
  • [This library](https://www.npmjs.com/package/module-alias) might also be helpful. – Cully Mar 15 '21 at 04:30

1 Answers1

0

You can use module.exports object to make your function accessible in another file.

let's say you have defined 2 functions in register.js as follows

const registerfunction1=()=>{
    console.log("console registerfunction1")
}

const registerfunction2=()=>{
    console.log("console registerfunction2")
}

module.exports={
    registerfunction1,
    registerfunction2
}

Now you can call these functions any file by using the node require as follows. for example

//importing register module
const register=require('./register');

const loginFunction=()=>{
    // calling function defined in register
    register.registerfunction1();
    console.log("loginFunction");
};

//calling function
loginFunction();
Dharman
  • 30,962
  • 25
  • 85
  • 135
santhosh
  • 261
  • 2
  • 8