Javascript Node.js,使用async/await和readline.on函数
我想读取一个有kye和值的文件 我使用“readline”逐行读取并将其存储到map对象 但它不起作用,只显示“未定义” 你们有没有办法解决这个问题 提前多谢Javascript Node.js,使用async/await和readline.on函数,javascript,node.js,readline,Javascript,Node.js,Readline,我想读取一个有kye和值的文件 我使用“readline”逐行读取并将其存储到map对象 但它不起作用,只显示“未定义” 你们有没有办法解决这个问题 提前多谢 #!/usr/bin/env node const fs = require('fs'); const readline = require('readline'); const hg = require('./js/funtions.js'); if (require.main === module) { const args =
#!/usr/bin/env node
const fs = require('fs');
const readline = require('readline');
const hg = require('./js/funtions.js');
if (require.main === module) {
const args = process.argv
var propertiesPath;
if(args.length >= 3){
propertiesPath = args[2];
}else {
console.log("No properties path");
process.exit(1);
}
if (propertiesPath.includes("-p")) {
propertiesPath = propertiesPath.replace("-p","");
}
const file = readline.createInterface({
input: fs.createReadStream(propertiesPath),
output: process.stdout,
terminal: false
});
var map = new Map();
var tokens,key,value;
file.on('line', (line) => {
tokens = line.split("=")
key = tokens[0];
value = tokens[1];
map.set(key,value);
});
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
}
在readline.on函数中使用async/await
在代码中不使用wait
/async
除此之外,file.on('line',…)
为流遇到的每一行file.on('line')
注册一个要调用的回调,这是异步发生的。由于这两行代码是在readline
找到文件中的任何一行之前执行的:
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
如果要在流读取所有行之后执行这两行代码,则需要在close
事件中执行:
file.on('close', () => {
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
});
在做了研究之后。
我决定不使用async/await函数。
所以我使用了一个简单的逻辑来读取文件并解析映射对象。
这是我的密码
#!/usr/bin/env node
const fs = require('fs');
const readline = require('readline');
const hg = require('./js/funtions.js');
if (require.main === module) {
const args = process.argv
var propertiesPath;
if(args.length >= 3){
propertiesPath = args[2];
}else {
console.log("No properties path");
process.exit(1);
}
if (propertiesPath.includes("-p")) {
propertiesPath = propertiesPath.replace("-p","");
}
var lines = require('fs').readFileSync(propertiesPath, 'utf-8')
.split('\n')
.filter(Boolean);
var map = new Map();
var tokens,key,value;
for (var i = 0; i < lines.length; i++) {
tokens = lines[i].split("=")
key = tokens[0];
value = tokens[1];
map.set(key,value);
}
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
}
#/usr/bin/env节点
常数fs=要求('fs');
const readline=require('readline');
const hg=require('./js/funtions.js');
if(require.main==模块){
常量args=process.argv
var属性路径;
如果(参数长度>=3){
propertiesPath=args[2];
}否则{
log(“无属性路径”);
过程。退出(1);
}
if(propertiesPath.includes(“-p”)){
propertiesPath=propertiesPath.replace(“-p”,”);
}
var line=require('fs').readFileSync(propertiesPath,'utf-8')
.split(“\n”)
.过滤器(布尔值);
var map=newmap();
var标记、键、值;
对于(变量i=0;i
非常感谢。但是我仍然需要使用“jsonPath”来完成其他工作。在关闭功能之外。jsonPath仍然显示未定义。@HaniLee这与您的
console.log(jsonPath)问题相同在读取行之前,调用close
回调函数外部的code>。异步代码就是这样工作的。您应该研究异步代码的工作原理,以及如何使用异步代码的可能性,例如,将承诺与await
和async
结合使用。