【问题标题】:Own Node.js project installed globally on own system在自己的系统上全局安装自己的 Node.js 项目
【发布时间】:2013-07-06 19:07:50
【问题描述】:

背景

我是 Node.js 的新手,所以请不要讨厌..

我发现 NPM 非常有用,因为我可以全局安装 Node.js 包,然后像独立的、可用路径应用程序一样使用它们。

这确实可以在 Windows 上运行,这让我很惊讶。

例如,我通过 npm install -g uglifyjs 以这种方式安装了 UglifyJS,现在我可以从系统中的任何位置运行它,从控制台通过 uglifyjs <rest of command>(不是 node uglifyjs .. 或其他)。

我想创建自己的独立 Node.js 应用程序。我如何被星宿?我在这里问是因为大多数教程只介绍了如何编写一个简单的脚本然后运行它 va node(我已经介绍过)


我当前的配置

package.json

{
    "name": "hash",
    "version": "1.0.0",
    "author": "Kiel V.",
    "engines": [
        "node >= 0.8.0"
    ],
    "main": "hash.js",
    "dependencies": {
        "commander" : "1.2.0"
    },
    "scripts": {
        "start": "node hash.js"
    }
}

hash.js

var crypto = require('crypto'),
    commander = require('commander');

/* For use as a library */
function hash(algorithm, str) {
    return crypto.createHash(algorithm).update(str).digest('hex');
}
exports.hash = hash;


/* For use as a stand-alone app */
commander
    .version('1.0.0')
    .usage('[options] <plain ...>')
    .option('-a, --algorithm [algorithm]', 'Hash algorithm', 'md5')
    .parse(process.argv);

commander.args.forEach(function(plain){
    console.log( plain + ' -> ' + hash(commander.algorithm, plain) );
});

问题:

假设我在node-hash 目录中只有这两个文件。我如何安装这个项目,以便稍后我可以通过hash -a md5 plaintextcmd.exe 中运行它,就像安装 coffescript、jslint 等一样?

【问题讨论】:

  • 您是在问如何编写自己的 npm 模块以便全局安装它?
  • @AndyD 是的,请检查更新

标签: javascript windows node.js npm


【解决方案1】:

你必须在 package.json 和 hash.js 中添加一些代码,然后你可以运行这个命令从本地文件夹安装包。

npm install -g ./node-hash

package.json

{
    "name": "hash",
    "version": "1.0.0",
    "author": "Kiel V.",
    "engines": [
        "node >= 0.8.0"
    ],
    "bin": {
        "hash": "hash.js"
    },
    "main": "hash.js",
    "dependencies": {
        "commander" : "1.2.0"
    },
    "scripts": {
        "start": "node hash.js"
    }
}

hash.js

#!/usr/bin/env node

var crypto = require('crypto'),
    commander = require('commander');

/* For use as a library */
function hash(algorithm, str) {
    return crypto.createHash(algorithm).update(str).digest('hex');
}
exports.hash = hash;


/* For use as a stand-alone app */
commander
    .version('1.0.0')
    .usage('[options] <plain ...>')
    .option('-a, --algorithm [algorithm]', 'Hash algorithm', 'md5')
    .parse(process.argv);

commander.args.forEach(function(plain){
    console.log( plain + ' -> ' + hash(commander.algorithm, plain) );
});

【讨论】:

  • 看起来很有前途,但是 hashbang 让我担心我的目标是 Windows 兼容性!
  • 当我们在 package.json 中使用 bin 字段时,npm 会为我们处理这个问题。
猜你喜欢
  • 2012-09-02
  • 2019-11-20
  • 1970-01-01
  • 2022-01-22
  • 2020-05-12
  • 1970-01-01
  • 2012-04-16
  • 2017-09-30
  • 2014-10-02
相关资源
最近更新 更多