У меня есть три JS файла, работающих под Node.JS. - сервер. js - файл основного сервера - bidMgr. js - вспомогательный файл - hand. js - еще один вспомогательный файл
Это файлы Express внутреннего сервера. Все находятся в одном каталоге. hand. js экспортирует функцию с именем show:
exports.show = function(hand) {...}
сервер. js экспортирует функцию с именем announceBid:
exports.announceBid = function(newBid) {...}
bidMgr. js хочет вызвать оба из эти функции. Таким образом, требуется каждый из модулей:
const handModule = require(__dirname + "/hand.js");
const serverModule = require(__dirname + "/server.js");
bidMgr. js вызывает функцию show, как показано:
handModule.show(players['North'].hand);
Но когда bidMgr. js пытается вызвать announceBid функция как показано:
serverModule.announceBid(bidStr.charAt(0) + suit);
Я получаю эту ошибку: /home/Documents/FullStack/WebDevelopment/bid-server/bidMgr.js:212 serverModule.announceBid (nextBid.level + nextBid.suit); Ошибка типа: serverModule.announceBid не является функцией
Я не вижу никакой разницы в том, как эти функции экспортируются и требуются. И все же один работает, а другой нет. Я просмотрел десятки постов в StackOverflow и попробовал все предложенные решения, но безуспешно.
Мое единственное предположение, что сервер. js код также должен вызывать функции, экспортируемые bidMgr. js. То есть код сервера. js включает команду:
const bidMgr = require(__dirname + "/bidMgr.js");
Может быть проблема в циклической зависимости?
Ниже приведены фрагменты кода из каждого из 3 файлов. Я включил в фрагменты операторы require, которые используются, каждую экспортируемую функцию из файла и способ вызова этой функции в другом файле. В итоге: - сервер. js экспортирует announceBid (), который вызывается в bidMgr. js - bidMgr. js экспортирует processHumanBid (), который вызывается на сервере. js - hand. js экспортирует конструктор Hand (), который вызывается в bidMgr. js Все используют экспорт / требуют семантики. Работает вызов Hand () в NewGame () в bidMgr. js. Вызов announceBid () в processHumanBid () в bidMgr. js приводит к ошибке.
From server.js
---------------
// jshint esversion:6
const bidMgr = require(__dirname + "/bidMgr.js");
const express = require("express", "4.17.1");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
var connections = [],
history = [],
lastMessageId = 0,
uptimeTimeout = 10 * 1000,
totalRequests = 0;
function removeConnection(res) {
var i = connections.indexOf(res);
if (i !== -1) {
connections.splice(i, 1);
}
console.log("Removed connection index " + i);
}
function broadcast(event, message) {
message = JSON.stringify(message);
++lastMessageId;
history.push({
id: lastMessageId,
event: event,
message: message
});
connections.forEach(function (res) {
sendSSE(res, lastMessageId, event, message);
});
}
exports.announceBid = function(newBid) {
const bidStr = newBid.level.toString() + newBid.suit;
broadcast('bid', bidStr);
}
From bidMgr.js
---------------
// jshint esversion:6
// Require the card module
const card = require(__dirname + "/card.js");
// Require the deck module
const deck = require(__dirname + "/deck.js");
// Require the hand module
const handModule = require(__dirname + "/hand.js");
// Require the player module
const playerModule = require(__dirname + "/player.js");
const serverModule = require(__dirname + "/server.js");
function processHumanBid(bidStr) {
const level = Number(bidStr.charAt(0));
const suit = bidStr.charAt(1);
nextBid = {suit: suit, level: level};
console.log("Human bid " + nextBid.level + nextBid.suit + " for " + bidder);
serverModule.announceBid(bidStr.charAt(0) + suit);
}
function newGame() {
if (!allPlayersJoined) {
console.log("Cannot start a game without all the players");
return;
}
// Rotate the Dealer
dealer = playerModule.getNextPlayer(dealer);
console.log("Dealer is " + dealer);
bidder = dealer;
// Deal the cards
var dealtHands = [];
var bridgeHands = [];
// Get the dealer to pass out all the cards into 4 piles
dealtHands = deck.dealDeck();
// Oh yeah, we are playing bridge. Create 4 bridge hands using these piles
for (let i = 0; i < 4; i++) {
bridgeHands[i] = new handModule.Hand(dealtHands[i]);
};
}
From hand.js
------------
//jshint esversion:6
// Require the card module
const suitModule = require(__dirname + "/suit.js");
// Require the card module
const card = require(__dirname + "/card.js");
exports.Hand = function(dealtCards) {
this.handCards = [...dealtCards];
this.handCards.sort(function(a, b) {
if (a.index < b.index) {
return -1;
}
if (a.index > b.index) {
return 1;
}
// a must be equal to b
return 0;
});
this.hcPts = calcHCP(dealtCards);
calcDistribution(this, dealtCards);
this.totalPts = calcTotalPts(this);
this.openingBid = calcOpenBid(this);
this.player = null;
};