Search code examples
node.jshapi.js

Getting started with hapi.js


I am looking at making a simple hello world with the hapi.js tutorial.

I have installed hapi:

  1. npm init
  2. npm install hapi --save
  3. I get a large set of folders with files

I tried doing node index.js and that gave me errors. So I cd into node_modules and got another error when running node. I cd again into hapi and again got an error when running node index.js. I added all of the syntax from the tutorial.

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();

Not sure where I should be running index.js


Solution

  • The node_modules folder is used to store all the dependencies for your application (ie. express, hapi, etc). This would be similar to a lib (library) folder in other languages.

    When you download dependencies using npm install, the node_modules folder will get placed at the root of your project. Your source files can be placed anywhere within the root or within subfolders you create. They shouldn't however, be placed in the node_modules folder since it is meant for external dependencies.

    Contrary to the other answer, you're not restricted to executing the program in the root - you can execute it in any subfolder as well. When you run the program, if Node can't find the node_modules folder in the current directory, it will move up to a parent directory until it finds it. See Node's modules documentation.