Muy bien, he creado un proyecto de prueba para mostrar este error. El error es que Node JS no puede encontrar mi función getStr en mi objeto Another.
Este es el código:
var Another = require("./another.js");
var Other = require("./other.js");
var otherStr = Other.getStr();
console.log(otherStr);
other.js
var Another = require("./another.js");
var str = Another.getStr();
another.js
var Other = require("./other.js");
var str = "other String";
exports.getStr = function(){
return str;
}
Y esta es mi salida:
C:UsersAdminDesktopJS DEVNODE DEVservertest>node test.js
C:UsersAdminDesktopJS DEVNODE DEVservertestother.js:3
var str = Another.getStr();
^
TypeError: Object #<Object> has no method "getStr"
at Object.<anonymous> (C:UsersAdminDesktopJS DEVNODE DEVservertestot
her.js:3:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:UsersAdminDesktopJS DEVNODE DEVservertestan
other.js:1:75)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
C:UsersAdminDesktopJS DEVNODE DEVservertest>
Entonces, ¿cómo hago para que Node JS vea la función getStr de Otro en Otro?
Respuestas
2 para la respuesta № 1Lo que está tratando aquí es una dependencia circular. Node.js dejar carga módulos de forma circular, pero necesita diseñar su código para dar cuenta de ello. En términos generales, una dependencia circular es una señal de que el diseño adolece de algún defecto. En el código que ha mostrado en la pregunta, another
requiere other
pero no hace nada con él. Entonces, la solución más simple sería cambiar another
para que no requiera other
.
Si tiene que mantener la dependencia circular por algún motivo o si desea experimentar con dependencias circulares con fines de aprendizaje, esta sería otra posible solución:
var str = "other String";
exports.getStr = function(){
return str;
}
var Other = require("./other");
// Actually do something with Other down here.
Para el momento other
es requerido another
tendrá al menos getStr
disponible. Entonces esto se encarga del problema inmediato. Sin embargo, tenga en cuenta que su other
módulo no exporta nada, por lo que su test.js
el archivo aún fallará en var otherStr = Other.getStr();
Probablemente olvidó agregar esto:
exports.getStr = function(){
return str;
}
(Nota: he modificado el require
llama para que requiera other
sin el .js
sufijo. Generalmente, no desea poner sufijos en su require
llamadas. Desea poner un nombre de módulo que Node pueda resolver en un archivo, paquete u otra cosa).