开始 hapi.js

Getting started with hapi.js

我正在考虑使用 hapi.js 教程制作一个简单的 hello world。

我已经安装了hapi:

  1. npm init
  2. npm install hapi --save
  3. 我得到一大组包含文件的文件夹

我试过node index.js,结果出错。所以我 cd 进入 node_modules 并在 运行 node 时得到另一个错误。我 cd 再次进入 hapi 并在 运行 node index.js 时再次出现错误。我添加了教程中的所有语法。

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({ 
    host: 'localhost', 
    port: 8000 
});

// Add the route
server.route({
    method: 'GET',
    path:'/hello', 
    handler: function (request, reply) {
        reply('hello world');
    }
});

// Start the server
server.start();

不确定我应该在哪里 运行 index.js

您应该忽略 node_modules 目录。 npm 使用它来安装依赖项。您不应在该目录中进行任何更改。您的文件应位于项目根目录中:

your-project
  |__ node_modules
  |__ index.html

您需要在项目根目录中执行node index.js,在本例中为your-project

cd your-project
node index.js

node_modules 文件夹用于存储应用程序的所有依赖项(即 expresshapi 等)。这类似于其他语言中的 lib(库)文件夹。

当您使用 npm install 下载依赖项时,node_modules 文件夹将放置在项目的根目录下。您的源文件可以放在根目录或您创建的子文件夹中的任何位置。但是,它们不应该放在 node_modules 文件夹中,因为它用于外部依赖。

与其他答案相反,您不限于在根目录中执行程序 - 您也可以在任何子文件夹中执行它。当你 运行 程序时,如果 Node 在当前目录中找不到 node_modules 文件夹,它将向上移动到父目录,直到找到为止。参见 Node 的 modules documentation.