![](/img/trans.png)
[英]NodeJS - How to reference function in one require() file from another require() file?
[英]How to use a function from another file using require()
我在StackOverflow上发现的任何问题都没有回答此问题,也未提供解决方案。
我正在创建一个使用Spotify的API的应用程序。 我对JavaScript比较陌生,但是很长一段时间以来我一直是其他语言(特别是OO语言)的编码器。 我试图在我的项目中使用面向对象的代码来处理API。
我可能没有正确地理解如何做,但是这是我的基本理解。 我在一个名为smartspot.js
文件中拥有用于处理API的所有代码。 该文件的内部类似于以下内容。
/**
* Taps into the Spotify API to create a playlist with top songs from artists most like a certain artist.
* @param {string} _clientId the client ID code given to the user by Spotify.
* @param {string} _clientSecret the client secret code given to the user by Spotify.
* @param {string} _redirectUri a Redirect URI that has been white-listed by Spotify.
* @constructor creates a SmartSpot that can access the Spotify API.
*/
function SmartSpot(_clientId, _clientSecret, _redirectUri)
{
//initialize the variables (omitted)
var clientId = _clientId;
clientSecret = _clientSecret;
//etc...
//various irrelevant variables and functions are ommited.
this.foo = function(param)
{
//does stuff
};
//etc...
}
现在,我相信function SmartSpot(_clientId, _clientSecret, _redirectUri)
是一个构造函数(如Java和C ++等语言)。 如果我错了,请纠正我。 因此,假设它是构造函数,则需要在另一个文件中使用它:我的快速“ routes”文件。 它位于`routes / index.js'中。
在文件的顶部,我把这个
var SmartSpot = require('../SmartSpot'); //I have also tried require('../Smartspot.js');
//later on
var smartSpot = new SmartSpot(clientId, clientSecret, redirectUri);
//elsewhere
smartSpot.foo();
但是,编译器向我抱怨说:
TypeError: SmartSpot is not a function
at Object.<anonymous>
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
//etc...
我在这里想念什么? 我正在使用IntelliJ进行所有操作,这表明我需要创建一个函数,所以我这样做了,并且它在index.js
文件中创建了构造函数/函数。 我想将文件分开以使代码更易于理解和使用。
如果您需要回答我遗漏的问题,请告诉我。
在亚历山大·麦克斯(Alexander Max)的帮助下,环顾四周后,我发现许多其他文件都module.exports = Something;
。
事实证明这是解决方案。 我把module.exports = SmartSpot;
在SmartSpot.js
文件的底部,然后将var SmartSpot = require('../SmartSpot');
在另一个文件的顶部。 现在,该文件已正确解释,并且能够从我的路线文件中使用它的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.