视频课程:带你入门Nodejs,提及了非常多的后端知识点

  • 发布时间: 2017年10月7日
  • 课程时长:193 分钟
  • 类别:后端
  • 课时:22

npm Resource:

npm模块管理器【阮一峰】

npm.com【官网】

从这里开始:Node.js 命令行程序开发教程


命令行交互任务

  • 读取 - 读取用户输入,解析输入了Javascript 数据结构并存储在内存中。

  • 执行 - 执行输入的数据结构

  • 打印 - 输出结果

  • 循环 - 循环操作以上步骤直到用户两次按下 ctrl-c 按钮退出。

加入环境变量

$ ./hello
hello world //更为简单的执行
$ hello
hello world

执行步骤:

Step 1, 在当前目录下新建 package.json

{
"name": "hello",
"bin": {
"hello": "hello"
}
} Step 2, run this. $ npm link

命令行参数

process.argv[...] 获取参数。

#!/usr/bin/env node
console.log('hello ', process.argv[2]);

新建进程

child_process模块:node.js是基于单线程模型架构,这样的设计可以带来高效的CPU利用率,但是无法却利用多个核心的CPU,为了解决这个问题,node.js提供了child_process模块。

#!/usr/bin/env node
var name = process.argv[2];
var exec = require('child_process').exec; var child = exec('echo hello ' + name, function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});

Shell的调用

安装 ---->

npm install --save shelljs

shelljs 模块:重新包装了 child_process,调用系统命令更加方便。它需要安装后使用。

#!/usr/bin/env node
var name = process.argv[2];
var shell = require("shelljs"); shell.exec("echo hello " + name);  // 非全局模式,有点是函数模式

全局模式:允许直接在脚本中写 shell 命令。

require('shelljs/global');

if (!which('git')) {
echo('Sorry, this script requires git');
exit(1);
} mkdir('-p', 'out/Release');
cp('-R', 'stuff/*', 'out/Release'); cd('lib');
ls('*.js').forEach(function(file) {
sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
sed('-i', /.*REMOVE_THIS_LINE.*\n/, '', file);
sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat('macro.js'), file);
});
cd('..'); if (exec('git commit -am "Auto-commit"').code !== 0) {
echo('Error: Git commit failed');
exit(1);
}

Shell的参数处理

安装 ---->

$ npm install --save yargs

yargs 模块:yargs 模块能够解决如何处理命令行参数

#!/usr/bin/env node
var argv = require('yargs').argv; console.log('hello ', argv.name);

方便提取参数。

$ hello --name=tom
hello tom $ hello --name tom
hello tom

进一步,支持多个别名(短参数,长参数)。

#!/usr/bin/env node
var argv = require('yargs')
.alias('n', 'name')      # 指定 name 是 n 的别名
.argv; console.log('hello ', argv.n); 

更为奇巧的,console.log(argv._),可以获取非连词线开头的参数。

$ hello A -n tom B C
hello tom
[ 'A', 'B', 'C' ]

命令行参数的配置

  • demand:是否必选
  • default:默认值
  • describe:提示

更多参数处理选项

#!/usr/bin/env node
var argv = require('yargs')
.demand(['n'])     // n参数不可省略
.default({n: 'tom'})    // 且默认值为tom
.describe({n: 'your name'})
.argv; console.log('hello ', argv.n);

options 方法允许将所有这些配置写进一个对象,{ }内就不用再写那么多重复的"n"了。

#!/usr/bin/env node
var argv = require('yargs')
.option('n', {
alias : 'name',
demand: true,
default: 'tom',
describe: 'your name',
type: 'string'
})
.argv; console.log('hello ', argv.n);

判断有没有该参数

可以用 boolean 方法指定这些参数返回布尔值。

#!/usr/bin/env node
var argv = require('yargs')
.boolean(['n'])
.argv; console.log('hello ', argv.n);

有该参数,返回true;否则,返回false。

$ hello
hello false
$ hello -n
hello true
$ hello -n tom
hello true

boolean 方法也可以作为属性,写入 option 对象。

#!/usr/bin/env node
var argv = require('yargs')
.option('n', {
boolean: true
})
.argv; console.log('hello ', argv.n);

帮助信息

yargs 模块提供以下方法,生成帮助信息。

usage:  用法格式
example:提供例子
help: 显示帮助信息
epilog: 出现在帮助信息的结尾 

希望达到的效果:

$ hello -h

Usage: hello [options]

Options:
-f, --name your name [string] [required] [default: "tom"]
-h, --help Show help [boolean] Examples:
hello -n tom say hello to Tom copyright 2015

实现方式:

#!/usr/bin/env node
var argv = require('yargs')
.option('f', {
alias : 'name',
demand: true,
default: 'tom',
describe: 'your name',
type: 'string'
})
.usage('Usage: hello [options]')
.example('hello -n tom', 'say hello to Tom')
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
.argv; console.log('hello ', argv.n);

子命令

yargs 模块还允许通过 command 方法,设置 Git 风格的子命令。

$ hello morning -n tom
Good Morning
hello tom

实现方式就是使用两次command(...),或者再与 shellojs 模块结合起来

#!/usr/bin/env node
require('shelljs/global');
var argv = require('yargs')
.command("morning", "good morning", function (yargs) {
echo("Good Morning");
})
.command("evening", "good evening", function (yargs) {
echo("Good Evening");
})
.argv; console.log('hello ', argv.n);

子命令设置各自的参数形式:

每个子命令往往有自己的参数,这时就需要在回调函数中单独指定。回调函数中,要先用 reset 方法重置 yargs 对象。

#!/usr/bin/env node
require('shelljs/global');
var argv = require('yargs')
.command("morning", "good morning", function (yargs) {
echo("Good Morning");
var argv = yargs.reset()
.option("m", {
alias: "message",
description: "provide any sentence"
})
.help("h")
.alias("h", "help")
.argv; echo(argv.m);
})
.argv;

用法如下:

$ hello morning -m "Are you hungry?"
Good Morning
Are you hungry?

其他事项

(1)返回值

根据 Unix 传统,程序执行成功返回 0,否则返回 1 。

if (err) {
process.exit(1);
} else {
process.exit(0);
}

(2)重定向

Unix 允许程序之间使用管道重定向数据。

$ ps aux | grep 'node'

脚本可以通过监听标准输入的data 事件,获取重定向的数据。

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data) {
process.stdout.write(data);
});

下面是用法。

$ echo 'foo' | ./hello
hello foo

(3)系统信号

操作系统可以向执行中的进程发送信号,process 对象能够监听信号事件。

process.on('SIGINT', function () {
console.log('Got a SIGINT');
process.exit(0);
});

发送信号的方法如下。

$ kill -s SIGINT [process_id]

[Node.js] 02 - Read Eval Print Loop的更多相关文章

  1. Node.js 事件循环(Event Loop)介绍

    Node.js 事件循环(Event Loop)介绍 JavaScript是一种单线程运行但又绝不会阻塞的语言,其实现非阻塞的关键是“事件循环”和“回调机制”.Node.js在JavaScript的基 ...

  2. vue 之node.js 02

    文档 铺垫 以前网页制作web1.0 如今是web2.0-->交互式操作 前端工具 grunt gulp webpack :打包机 作用:将项目中的js,css,img,font,html等进行 ...

  3. Node.js Learning Notes

    简介 简单的说 Node.js 就是运行在服务端的 JavaScript. Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台. Node.js是一个事件驱动I/O服务 ...

  4. node js学习(二)——REPL(交互式解释器)

    1.简介 Node.js REPL(Read Eval Print Loop:交互式解释器) 表示一个电脑的环境,类似 Window 系统的终端或 Unix/Linux shell,我们可以在终端中输 ...

  5. Node.js入门 NPM

    参考一 Node入门  七天学会NodeJS  Node.js v4.2.4 手册 & 文档  Node.js 教程 node.js摸石头系列 从零开始学习node.js   What is ...

  6. Node.js实战(七)之交互式解释器

    Node.js REPL(Read Eval Print Loop:交互式解释器) 表示一个电脑的环境,类似 Window 系统的终端或 Unix/Linux shell,我们可以在终端中输入命令,并 ...

  7. 4、Node.js REPL(交互式解释器)

    Node.js REPL(Read Eval Print Loop:交互式解释器) 表示一个电脑的环境,类似 Window 系统的终端或 Unix/Linux shell,我们可以在终端中输入命令,并 ...

  8. node.js cmd常用命令

    cmd1.c:如果我们想访问c盘,那么我们需要在命令行中输入c:就行了 2.cd..cd..就可以返回上层目录 3.cd mmcd mm即可访问mm文件夹 4.dir如果想查看该文件夹下有哪些文件,则 ...

  9. node.js入门之三

    Node.js REPL(交互式解释器) Node.js REPL(Read Eval Print Loop:交互式解释器) 表示一个电脑的环境,类似 Window 系统的终端或 Unix/Linux ...

随机推荐

  1. centos npm 安装后 command not found

    ok,

  2. windows环境下面批量新建文件夹

    md D:批量新建文件夹\2026 md D:批量新建文件夹\2030 md D:批量新建文件夹\2032 md D:批量新建文件夹\1835 md D:批量新建文件夹\1832 电脑桌面新建文档 - ...

  3. LM && NTLM && ophcrack && RainBow table

    Windows密码的加密方式:Windows 主要使用以下两种(包含但不限于)算法对用户名和密码进行加密:分 别是LanManager(LM)和NTLM,LM只能存储小于等于14个字符的密码hash, ...

  4. XMPP使用简介--登录

    在现阶段的通信服务中,各种标准都有,因此会出现无法实现相互连通,而XMPP(Extensible Message and presence Protocol)协议的出现,实现了整个及时通信服务协议的互 ...

  5. SpringBoot(八):系统错误统一拦截器

    在日常 web 开发中发生了异常,往往需要通过一个统一的 异常处理,来保证客户端能够收到友好的提示.本文将会介绍 Spring Boot 中的 全局统一异常处理. Springboot的全局异常查是通 ...

  6. JFinal提示:java.lang.RuntimeException: dao 只允许调用查询方法

    public class UserModel extends Model<UserModel>{ public static final UserModel userDao = new U ...

  7. Android 里的数据储存

    数据持久化 关于数据储存,这个话题已经被反复讨论过很多次了,我是不建议把网络存储这种方式纳入到数据储存的范围的,因为这个和Android没多少关系,因此就有如下的分类: 本地储存(也称之为数据持久化, ...

  8. ios中输入框的父类--文本框,DataPick,pickerview

    父控制器 #import <UIKit/UIKit.h> #import "ScrollViewExt.h" @interface BaseKeyBoardCtrl : ...

  9. MySQL 5.6新特性 -- Index Condition Pushdown

    Index Condition Pushdown(ICP)是针对mysql使用索引从表中检索行数据时的一种优化方法.   在没有ICP特性之前,存储引擎根据索引去基表查找并将数据返回给mysql se ...

  10. HTTP Status 500 - Unable to create directory

    分析原因: 例如:java web项目 上传图片创建文件夹cd /data/apps/static-web/sjk/driver/attachment/编号/文件名称.jpg 在创建文件目录 /dat ...