首页 > 解决方案 > 导出/要求不适用于 Node.JS 文件

问题描述

我在 Node.JS 下运行了三个 JS 文件。
- server.js - 主服务器文件
- bidMgr.js - 帮助文件
- hand.js - 另一个帮助文件

它们是后端服务器 Express 文件。所有都在同一个目录中。
hand.js 导出一个名为 show 的函数:

    exports.show = function(hand) {...}

server.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);
TypeError: serverModule.announceBid 不是函数

我看不出这些函数的导出和需要方式有什么不同。然而,一个有效,另一个无效。我查看了 StackOverflow 上的数十篇帖子并尝试了所有建议的解决方案,但均未成功。

我唯一的猜测是 server.js 代码还需要调用 bidMgr.js 导出的函数。也就是说,server.js 代码包含以下命令:

    const bidMgr = require(__dirname + "/bidMgr.js");

问题可能是循环依赖吗?

以下是 3 个文件中每个文件的代码片段。
我在片段中包含了所使用的 require 语句、从文件中导出的每个函数,以及如何在不同的文件中调用该函数。
总结:
- server.js 导出announceBid(),在bidMgr.js 中调用
-bidMgr.js 导出processHumanBid(),在server.js 中调用
- hand.js 导出Hand() 构造函数,在bidMgr.js

都使用 export/require 语义。
在bidMgr.js 中的NewGame() 中调用Hand() 有效。
在bidMgr.js 中调用processHumanBid() 中的announceBid() 会导致错误。

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;
};

标签: javascriptnode.jsexport

解决方案


我建议你不要在 server.js (announceBid) 中使用 from 调用函数。要向客户端发送响应,您可以使用如下文件:

apiResponse.js:

'use sctrict';
var HttpStatus = require('http-status-codes');

exports.sendSucces = function (res, data) {
    try {
        if (res) {
            if(data)
                res.status(HttpStatus.OK).json(data);
            else
                res.status(HttpStatus.OK).send();
        }
    } catch (error) {
        //log error
    }
}

推荐阅读