Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary file in npm package

I try to create an npm package, which can be started as a command from shell. I have package.json

{
  "name": "myapp",
  "version": "0.0.6",
  "dependencies": {
    "async": "",
    "watch": "",
    "node-promise": "",
    "rmdir": "",
    "should": "",
    "websocket": ""
  },
  "bin": "myapp"
}

and myapp

#!/bin/bash

path=`dirname "$0"`
file="/myapp.js"

node $path$file $1 &

But I get an error:

module.js:340
    throw err;
          ^
Error: Cannot find module '/usr/local/bin/myapp.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

The problem is that myapp.js is in another directory. How can I get this directory name from my script? Or maybe there is better way to do this?

like image 546
ciembor Avatar asked Jun 06 '14 13:06

ciembor


1 Answers

Actually, you can put your myapp.js file into bin.
So, the bin key in package.json file should be like this :

"bin": { "myapp" : "<relative_path_to_myapp.js>/lib/myapp.js" }

At the first line in myapp.js, you must add this shebang line :

#!/usr/bin/env node

It tells the system to use node to run myapp.js.


... Or if you don't want to call myapp.js directly, you can create a script like this to be your executable file :

#!/usr/bin/env node

var myapp = require('<relative_path_to_myapp.js>/myapp.js');
myapp.doSth();

and in package.json :

"bin" : { "myapp" : "<relative_path_to_the_script>/script.js" }

By doing this either way, you can avoid finding the path to your nodemodule.


But... if you insist to use your old myapp bash script, then you can find the path to the module with this :

myapp_path=$( npm explore -g myapp -- "pwd" )

Hope these help :D

like image 127
3329 Avatar answered Oct 24 '22 12:10

3329