Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

javascript - node.js throws error when I try to require local module

Where am I going wrong while requiring a local module? Below are my code snippets for requiring a local module. I have placed the game.js file in the following path /public/javascript/game.js whereas the app.js is being placed in the following path /app.js

//game.js
let players = [];
let selectedPlayers = [];
let remainingPlayers = 11;

for(var i=0; i<2; i++){
  players.push($(".card > button").eq(i).attr("value"));
}

exports.players = players;
//app.js
const express = require("express");
const bodyParser = require("body-parser");
const mySql = require("mySql");
const game = require("./game");

const app = express();

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');

app.get("/play", function(req, res){
  res.render("PlayGame");
  console.log(game.players);
});

app.listen(process.env.PORT || 3000, function(req, res){
  console.log("Listening on port 3000");
});

When I run this, I get the following error in my terminal

internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module './game'
Require stack:
- C:UsersakashDesktopFantasyCricketapp.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:UsersakashDesktopFantasyCricketapp.js:4:14)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'C:\Users\akash\Desktop\FantasyCricket\app.js' ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

They are not on the same folder, so your require must be:"

const game = require("./public/javascript/game");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...