簡體   English   中英

導出/要求不適用於 Node.JS 文件

[英]Export/Require not working for Node.JS files

我在 Node.JS 下運行了三個 JS 文件。
- server.js - 主服務器文件
-bidMgr.js - 幫助文件
- hand.js - 另一個幫助文件

它們是后端服務器 Express 文件。 所有都在同一個目錄中。
hand.js 導出一個名為 show 的 function:

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

server.js 導出一個名為announceBid 的function:

    exports.announceBid = function(newBid) {...}

bidMgr.js 想要調用這兩個函數。
所以它需要每個模塊:

    const handModule = require(__dirname + "/hand.js");
    const serverModule = require(__dirname + "/server.js");

bidMgr.js 調用 show function 如圖:

    handModule.show(players['North'].hand);

但是當bidMgr.js 嘗試調用announceBid function 時,如圖所示:

    serverModule.announceBid(bidStr.charAt(0) + suit);

我收到此錯誤:
/home/Documents/FullStack/WebDevelopment/bid-server/bidMgr.js:212 serverModule.announceBid(nextBid.level + nextBid.suit);
類型錯誤:serverModule.announceBid 不是 function

我看不出這些函數的導出和需要方式有什么不同。 然而,一個有效,另一個無效。 我查看了 StackOverflow 上的數十篇帖子並嘗試了所有建議的解決方案,但均未成功。

我唯一的猜測是 server.js 代碼還需要調用 bidMgr.js 導出的函數。 也就是說,server.js 代碼包含以下命令:

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

問題可能是循環依賴嗎?

以下是 3 個文件中每個文件的代碼片段。
我在片段中包含了所使用的 require 語句,每個都從文件中導出 function,以及如何在不同的文件中調用 function。
總之:
- 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;
};

我建議你不要在 server.js (announceBid) 中調用 function。 要向客戶端發送響應,您可以使用如下文件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM