Reputation: 1851
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?
Upvotes: 4
Views: 17393
Reputation: 809
Or simply you can use module.exports
module.exports = {
shorten: function(url) {
//some process here
return {
success: true,
data: url
}
},
checkLink: function (any,values,here) {
//some code
return { value };
}
}
In the request use as follow
let someShorten= require("./place/to/file");
someShorten.shorten('http://myurl.com');
Upvotes: 0
Reputation: 2969
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
Upvotes: 9
Reputation: 21756
Currently you are exporting only one function which is module.exports = shorten
.
You need to export checkLink(url)
as well same as shorten
like below:
module.exports = checkLink
Another way to combine both exports like below:
module.exports = {
shorten,
checkLink
}
Here is one nice article about Exporting and Importing modules in nodejs.
Upvotes: 0