我正在尝试安装我刚用npm编写的自定义模块。我希望能够像计算机上的任何其他命令一样运行它。
它被称为“nawk”
的package.json
{
"name": "nawk",
"preferGlobal": true,
"version": "0.0.1",
"author": "My Name <xxxxxxxxxx@gmail.com>",
"description": "a simpler version of awk",
"bin": {
"nawk": "./index.js"
},
"scripts": {
"start": "node index"
},
"dependencies" : {
},
"license": "MIT",
"engines": {
"node": ">=0.6"
}
}
index.js
require('fs');
var readline = require('readline');
var args = process.argv;
args.shift();
args.shift();
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function (line) {
var message = '';
var tokens = line.split(/\s+/);
process.argv.forEach(function(index){
index = +index;
var val = null;
if(index >= 0){
val = tokens[+index];
} else {
val = tokens[tokens.length + +index - 1];
}
if(val){
message += val + '\t';
}
});
if(message){
console.log(message);
}
});
我可以很好地安装它,但是当我去运行它时,我在第一行遇到语法错误。当我从目录运行时,这不会发生。
我像这样安装
> sudo npm install -g $(pwd)
然后我尝试像这样运行它。
> echo hi how are you | nawk 0 -1
/usr/local/share/npm/bin/nawk: line 1: syntax error near unexpected token `'fs''
/usr/local/share/npm/bin/nawk: line 1: `require('fs');'
答案 0 :(得分:8)
我需要将它添加到索引文件的顶部
#!/usr/bin/env node
require('fs');
var readline = require('readline');
...