Ad

Npm Not Creating ./node_modules For Own Local Install Package

- 1 answer

I am working through a Hello World example for developing a Nodejs extension using C++. Everything works and I can run the example. However I want to use require('hello') instead of require('./build/Release/hello') which I understand needs the file to be placed in a node_modules folder. When I follow the instructions about using NPM Install to locally install a package the folder node_modules is not created ( After many hours I have developed a workaround but it is a mess ).

I am using Mac OS Mountain Lion and NPM version 1.2.17. NPM installs packages from the repository ( and uninstall ) both locally and globally without any problems. I have checked NPM root and it is pointing to a node_modules folder and re-installed NPM as suggested in a previous question. The files are as follows:

package.json

{
  "name": "HelloWorld",
  "version": "1.0.0",
  "description": "Nodejs Extension using C++",
  "main": "./build/Release/hello.node",
  "scripts": {
    "preinstall": "node-gyp rebuild",
    "preuninstall": "rm -rf build/*"
  },
  "repository": "",
  "readmeFilename": "README.md",
  "author": "",
  "license": ""
}

binding.gyp

{
  "targets": [
    {
      "target_name": "hello",
      "sources" : [ "src/hello.cc" ]
    }
   ]
}

hello.cc

#include <node.h>
#include <v8.h>

using namespace v8;


Handle<Value> Method(const Arguments& args) {
   HandleScope scope;
   return scope.Close(String::New("Hello, World!"));
}

void init(Handle<Object> exports) {
  exports ->Set(String::NewSymbol("hello"),
    FunctionTemplate::New(Method)->GetFunction());
}

NODE_MODULE(hello, init)

I feel that I am missing something simple due to my lack of experience in using NPM and therefore would appreciate any help.

Also, I am new to Stack Overflow and therefore any guidance on how I can improve any future questions will be gratefully received.

Ad

Answer

The name of the package is determined by the name property in package.json. The way you have it setup will work with

`require("HelloWorld")`

as you have

`"name": "HelloWorld"`

If you want it to be

`require("hello")`

simply change your package.json file to have

`"name": "hello"`

To your install question - how and where are you running npm install? I created a HelloWorldClient directory at the same level as HelloWorld and ran

`npm install ../HelloWorld/`

which worked fine. My client code (after changing the package name to hello) worked as well: test.js:

var hello = require('hello');
console.log(hello.hello());
Ad
source: stackoverflow.com
Ad