importing modules from other folders nodejs

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

Answers 1

  • 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();
    

Related Articles