【问题标题】:nodejs helloworld test app not runningnodejs helloworld 测试应用程序未运行
【发布时间】:2014-09-03 17:36:14
【问题描述】:

我是学习 node.js 的新手,我在 ubuntu 上下载了所有组件。我写了一个测试,helloworld 应用程序,但由于某种原因它不起作用。这是我的文件布局。

当我执行哪个nodejs时,终端返回/usr/bin/nodejs

当我执行 which npm 时,终端返回 /usr/bin/npm

我的 app.js 测试文件位于 /home/tarang/node/helloWorld

这里是 app.js 的源代码

//creating http server
var http = require('require');

http.createServer(function(req, res){
    res.writeHead(200, {'Context-Type': 'text/plain'});
    res.end('helloWorld');
}).listen(8000);

console.log('server running');

更新

当我执行 nodejs app.js 时,我得到以下错误

Error: Cannot find module 'require'
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> (/home/tarang/node/helloWorld/app.js:4:12)
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)

请解释一下,因为我是 ubuntu 和 nodejs 的新手。

谢谢!

更新

我需要更新到最新版本的 express、node 和 npm 吗?

【问题讨论】:

  • 刚刚更新。请看一看!

标签: javascript node.js ubuntu


【解决方案1】:

你想导入http模块,而不是require,所以

//creating http server
var http = require('http');

【讨论】:

  • 还有,为什么有些网站说我需要使用node app.js来执行,而我必须使用nodejs app.js来执行呢?这是版本问题吗?
  • Ubuntu节点包不规范,将可执行文件名改为nodejs。它应该node,但你必须与包维护者一起处理它。
  • 所以我想,如果它有效,它有效吗?我不用担心,对吧?
  • 是的,尤其是在您刚刚开始的时候。稍后您可以查看using a ppa。它通常是最新的。
  • 但它确实说我有最新版本的nodejs。 nodejs --version 返回 v0.10.25
【解决方案2】:

根据错误消息,require 模块丢失。

cd 到应用根目录,运行:

npm install --save

编辑:

嘿等等,你为什么是require('require')

我相信应该是require('http')

【讨论】:

  • 所以 cd 到 node 的安装位置,即 usr/bin/nodejs ?
  • 不,你的应用的根目录,我相信应该是/home/tarang/node/helloWorld
  • 终端返回“无法读取依赖项”。为什么这么复杂?
  • 所以我相信你还没有 package.json。在我编辑的几分钟后看到我的答案:D
  • 我想我还没有 package.json。我正在关注本教程。 code.tutsplus.com/tutorials/…
【解决方案3】:

问题可能是因为您在运行之前没有安装 require 模块。运行服务器前需要在命令行运行npm install require,否则找不到模块。

【讨论】:

  • 我刚刚这样做了,它返回了同样的错误。我不确定发生了什么。
  • 也可以全局安装:npm install -g require
  • 确认您现在有一个node_modules 目录与您的 app.js 位于同一目录中?
  • 我该怎么做?我真的很困惑。我认为错误是因为节点找不到一些必要的文件
  • ls -ltr 在ubuntu命令行上......既然如此,我不完全确定你为什么首先使用require?如果你只是想复制 Node 基础教程,你应该使用 http 模块,而不是 require 模块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 2017-10-15
  • 2019-01-26
  • 2019-07-19
  • 2013-04-25
  • 2011-01-20
  • 2015-03-28
相关资源
最近更新 更多