gpt4 book ai didi

javascript - Node.js "Error: Can not find module"

转载 作者:行者123 更新时间:2023-12-03 11:04:09 25 4
gpt4 key购买 nike

我正在学习 lynda.com 的 node.js 类(class),但无法找到导致“错误:找不到模块”的原因。从我所知道的一切来看,package.json 中有飞行模块。

到目前为止,一切都正常,所以我知道 node.js 已安装并正确运行。我运行此文件的方式是在命令行中键入“node app.js”。此外,所有文件都位于同一文件夹中。

这是控制台日志:

C:\Users\Jonathan\Desktop\flight>node app.js

module.js:340
throw err;
^
Error: Cannot find module './flight'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Users\Jonathan\Desktop\flight\app.js:1:76)
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 Function.Module.runMain (module.js:497:10)

C:\Users\Jonathan\Desktop\flight>

这是代码。

Package.json 文件

{
"name": "flight",
"version": "1.0.0",
"description": "a module for keeping track of a flight",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "JBaxter",
"license": "ISC"
}

index.js 文件

 var number, origin, destination;

exports.setNumber = function (num){
number = num;
};

exports.setOrigin = function (o){
origin = o;
};

exports.setDestination = function (d){
destination = d;
};

exports.getInfo = function() {
return {
number: number,
origin: origin,
destination: destination
};
};

app.js 文件

var flight = require('./flight');

flight.setOrgin('LAX');
flight.setDestination('DCA');
flight.setNumber(462);

console.log(flight.getInfo());

任何帮助都很棒。我认为 package.json 文件中的名称是您的模块,但也许我错了。提前致谢。

最佳答案

在您的情况下,“./flight”不会计算为index.js。

如果您创建子目录:

flight
- index.js

然后你可以 require("./flight") 并将其计算为“./flight/index.js”。

就您而言,您可以做的最简单的事情:

require("./index.js");

关于javascript - Node.js "Error: Can not find module",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27946797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com