我有一个看起来像这样的目录结构(两个文件夹都具有node_modules可用)
- task1
- src
- shorten.js
- task2
- src
- api.js
- server.js
Run Code Online (Sandbox Code Playgroud)
在shorten.js我有两个功能,即shorten(url)和checkLink(url)。在文件末尾,我有一些东西module.exports = shorten。
在api.js,我有一条线const shorten = require("../../task1/src/shorten");。如果仅shorten使用参数进行调用,就没有问题,但是当我尝试以checkLink类似方式进行调用时,问题就来了。
为了能够checkLink在task2的api.js内部调用,我该怎么办?
您还需要导出shortshort.js内的checkLink函数,以便可以从api.js中要求它。
在shortening.js内部,将您的module.exports更改如下:
module.exports = { shorten, checkLink }
Run Code Online (Sandbox Code Playgroud)
在api.js里面是这样的:
let myShortenFile = require ("../../task1/src/shorten")
myShortenFile.shorten() // to call shorten
myShortenFile.checkLink() // to call the checkLink
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
//更新:
由于OP指示他不能导出两个功能,而只想导出第一个功能,并且仍然可以访问第二个功能...
// 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4715 次 |
| 最近记录: |