如何在Node.js中将指定TypeScript代码转换为可运行的JavaScript代码
TypeScript逐行读取文件函数转JavaScript实现
这段TypeScript代码仅使用了类型注解做类型约束,没有用到TypeScript专属语法,直接移除所有类型标注即可得到可直接运行的JavaScript代码。
转换后的函数代码
async function readLines(filename, processLine) { return new Promise((resolve, reject) => { lineReader.eachLine(filename, (line, last, callback) => { if (!callback) throw new Error('panic'); processLine(line) .then(() => last ? resolve() : callback()) .catch(reject); }); }); }
前置依赖说明
- 你需要提前安装
line-reader依赖,可执行命令npm install line-reader完成安装 - 如果你的代码中用到了
delay函数,需要提前声明,简易实现参考如下:
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))
调用代码
和原有调用逻辑完全一致:
await readLines(filename, async (line) => { await delay(1000) some_other_func(line); });
如果你的运行环境不支持顶层await,可以将调用逻辑包裹在异步自执行函数中:
(async () => { await readLines(filename, async (line) => { await delay(1000) some_other_func(line); }); })()
内容的提问来源于stack exchange,提问作者j. cole
相关产品推荐
相关产品推荐

