请问,该如何写node.js的入口文件?

如何写node.js的入口文件


扬帆大鱼
浏览 889回答 3
3回答

阿晨1998

创建项目:新建一个文件夹,假设我们取名为tbjnodecd tbjnode然后初始化项目npm init现在,我们需要修改 package.json 文件1:删除main入口2:添加preferGlobal设为true:该选项会提示用户全局安装3:添加bin对象,用于建立索引:比如执行tbjname相当于执行index.js修改后的package.json如下:{"name": "tbjnode","version": "1.0.3","description": "tbj node project cli","preferGlobal": true,"keywords": ["file","search"],"bin": {"filesearch": "index.js"},"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "zhishui","license": "ISC"}bin下的filesearch用来指定filesearch命令执行的文件为index.js使用 npm link ,绑定全局,不用重新安装。好了,现在我们开始写一个功能,用来查询某个文件夹下是否有指定的文件。我们新建一个 index.js编写如下代码:#!/usr/bin/env nodevar exec = require('child_process').exec;// 获取用户输入内容var userArgv = process.argv.slice(2);var searchPath = userArgv[0];var searchFile = userArgv[1];var commond = "find ";// 判断用户输入是否错误if(userArgv.length !=2) {console.log("input commond link this 'filesearch filepath filename'");} else {commond += searchPath + ' -iname '+ searchFile;var child = exec(commond, function(err, stdout, stderr) {if(err) {throw err;}console.log(stdout);});}ok。现在开始测试一下: filesearch ./ package.json 。就可以看到结果了。但是现在TJ大神也做了一个特别酷的工具。 commanderAPI地址: commander API举例一个example:新建一个文件 testCommander.js然后在bin里,添加一个索引。bin: {"filesearch": "index.js","testC": "testCommander.js"}在 testCommander.js 写入以下代码:#!/usr/bin/env nodevar program = require('commander');program.version('0.0.1').option('-C, --chdir <path>', 'change the working directory').option('-c, --config <path>', 'set config path. defaults to ./deploy.conf').option('-T, --no-tests', 'ignore test hook')program.command('setup').description('run remote setup commands').action(function() {console.log("setup");});program.parse(process.argv);执行 testC -h ,就可以看到命令行结果。commander这里主要用了五个接口:1. version: 设定版本号2. option: 对该命令介绍以及一些参数的执行3. command: 新增一个子命令,执行``testC setup``4. description: 对该命令的描述5. action: 该子命令的要执行的操作。其他的操作请查看该文档接口。
打开App,查看更多内容
随时随地看视频慕课网APP