Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs access function from another file

Tags:

node.js

I have a directory structure which looks somewhat like this (both folders have node_modules available)

- task1
     - src
          - shorten.js
- task2
     - src
          - api.js
          - server.js

In shorten.js I have two functions namely shorten(url) and checkLink(url) . At the end of the file, I have something as module.exports = shorten.

In the api.js, I have a line const shorten = require("../../task1/src/shorten");. If I simply call shorten with the parameter, it is having no problems, but the problem comes when I try to call checkLink in a similar way.

What should I do in order to be able to call checkLink inside api.js of task2?

like image 322
Sparker0i Avatar asked Jan 02 '23 02:01

Sparker0i


1 Answers

You need to also export the checkLink function inside the shorten.js so you can then require it from the api.js...

Inside shorten.js change your module.exports to look like this:

module.exports = { shorten, checkLink }

Inside the api.js like this:

let myShortenFile = require ("../../task1/src/shorten")
myShortenFile.shorten() // to call shorten
myShortenFile.checkLink() // to call the checkLink

Hope this helps.

// UPDATE:

Since the OP has indicated he cannot export both functions and only wants to export 1 function and still have access to the second...

// shorten.js
const shorten = function(url, isCheckLink){
 if(isCheckLink){
  // Perform check link code
  return Result_of_check_link_function
 }
 else{
  return Result_of_shorten_function
 }
}

module.exports = shorten

// inside api.js
let myShortenFile = require ("../../task1/src/shorten")
myShortenFile.shorten('http://myurl.com') // to call shorten
myShortenFile.shorten('http://myurl.com', true) // pass true 
// as second argument to call the CheckLink function
like image 190
jremi Avatar answered Jan 05 '23 16:01

jremi