在刷华为OD的笔试题时,需要使用node。处理输入输出,会用到readline模块。
readline模块提供了一个接口 可以在可读流中读取数据
js
const readline = require('readline')
const rl = readline.createInterface({
	input: process.stdin,
})
rl.on('line', (input) => {
	console.log(input)
  if (input === 'exit') {
    rl.close()
  }
})
rl.on('close', () => {
	console.log('guanbi')
})使用异步迭代器的写法(华为面试题给的测试代码)
js
const readline = require('readline')
const rl = readline.createInterface({
	input: process.stdin,
})
const iter = rl[Symbol.asyncIterator]()
const getlLine = async () => {
	const { done, value } = await iter.next()
	return value
}
void (async () => {
	while ((line = await getlLine())) {
		console.log(line)
		if (line === 'exit') {
			rl.close()
		}
	}
})()
rl.on('close', () => {
	console.log('guanbi')
})立即执行函数前有的void关键字,其实加不加都会立即执行,但是还是有区别的。
void 表示不关心返回结果,只是想要触发异步操作,返回值始终是个undefined。
本地vscode 使用ts、 ts-node、nodemon、esmodule模块 调试 node代码 
全局安装 ts-node ts
shell
pnpm add -g ts-node typescript nodemon
pnpm add -D @types/node typescript设置package.json type字段为module
初始化 tsconfig文件
shell
tsc --inittsconfig.json 配置
json
{
	"compilerOptions": {
		"target": "ESNext" /* 编译出来的产物 */,
		"module": "ESNext", /* 指定编译产物的模块格式 */
		"strict": false,
		"esModuleInterop": true, /* 修复了一些 CommonJS 和 ES6 模块之间的兼容性问题 */
	},
	"include": ["."],
	"exclude": ["**/node_modules/**"],
	"ts-node": {
		"esm": true /* ts-node 支持 esm 只兼容node16版本 */
	}
}版本
shell
ts-node --version # v10.9.2
tsc --version # Version 5.4.5
node --version # v16.18.1
nodemon --version # 3.1.1ts-node 代码中使用 import 时,只支持的node版本是16,使用高版本就报错了
使用 require() 时,20版本的node也能用