Node 基础 5:调用接口

616 阅读2分钟

写命令行程序

//cli.ts
const program = new commander.Command()
import {translator} from './main';

program
  .version('0.0.1')
  .name('tl')
  .usage('<English>')
  .argument('<English>')
  .action((english) => {  
    translator(english)
  });

program.parse();

用 Node.js 的 https.request 向百度翻译的服务器发 https 请求

const https = require('https');

const options = {
  hostname: 'api.fanyi.baidu.com',  //网址
  port: 443,
  path: '/api/trans/vip/translate?' + query,  //路径加查询参数
  method: 'GET'
};

const request = https.request(options, (response: IncomingMessage) => {
  let chunks:Buffer[] = [];
  response.on('data', (chunk:Buffer) => {
    chunks.push(chunk);
  });

request.end();

构造查询参数

使用 MD5 验证方式,使用 URLSearchParams 类构造 query

yarn add js-md5
yarn add --dev @types/js-md5  //引入 js-md5 的 ts 声明,否则 ts 不知道 md5 是什么东西


import md5 from 'js-md5';

let appid = '???';
const appSecret = '???'
let salt = Math.random();
let sign = md5(appid + word + salt + appSecret);

const query = new URLSearchParams([
    ['q', word],
    ['from', from],
    ['to', to],
    ['appid', appid],
    ['salt', salt],
    ['sign', sign]
]).toString();

表驱动编程

const errorMap: ErrorMap = {
  52000: '成功',
  52001: '请求超时,请重试 ',
  52002: '系统错误,请重试',
};

if (object.error_code) {
  console.error(errorMap[object.error_code] || object.error_msg);  //表驱动
  
  process.exit(2);  //响应结束之后,要结束进程
} 

ts 类型报错

errorMap 是一个对象,里面 key 的个数是固定的,所以不能把一个未知的字符串放在该对象里面,如果这个字符串表示的 key 不在 errorMap 里面,那么就是访问了一个意外的 key,所以需要声明

type errorMap = {
  [key:string]:string   //虽然 errorMap 对象只有三个 key,但是它的 Key 可以是任意字符串
}

image.png

上传 npm

node 不能直接运行 ts 文件,需要先将 ts 文件编译成 js 文件,再上传到 npm

编译 ts 文件

1、yarn add global typescript

2、tsc --init

3、更改 tsconfig.json 文件:

"outDir": "dist/",  //有代码生成就放在 dist 目录 

4、如果 ts 编译过程中报错,又不知道变量是什么类型时,可以先删除 tsconfig.json

"noImplicitAny": false,  //默认是 true ,改成 false 可以随便写 ts 代码,可以临时用
 
console.log(chunk.constructor)  //对于不知道是什么类型的变量,可以这样看它的类
//如果 ts 过不了,可先将 tsconfig.json 删除,让代码运行起来,再想办法弄清楚类型

5、更改 package.json 文件:

"version": "1.0.0",
"main": "dist/main.js",  
"files": [        //要上传哪些文件
  "dist/**/*.js"    
],
"bin": {                 //添加命令行快捷键,从 npm 上下载了这个包,才能用这个快捷键
  "tl": "dist/cli.js"    //命令行输入 tl ,相当于执行 node dist/cli.js 命令
},

6、给 cli.ts 添加 node 的 shebang ,指明文件用 node 运行:

//cli.ts
#!/usr/bin/env

7、npm publish

本地运行,添加 alias

如果只是在本地运行,不上传到 npm 的话,要用快捷键的话,需要配置 alias 。

vi ~/.bashrc
//按 o 键,进入文本编辑;
//注意:用绝对路径,修改下划线;
alias f="ts-node-dev D:/demoes/translator-1/src/cli.ts"
//文本编辑完成后,光标移动到末行行尾,会退出文本编辑模式
//:wq  是先保存,再推出
:wq  
source ~/.bashrc

//这时就可以在命令行使用快捷键
t round