我刚刚使用 Node JS 创建了一个非常简单的 Web 服务器,它询问 JSON 文件的名称,然后循环通过它并将其中的某些键作为“格式化”文本文件提供。
代码:
var http = require('http'),
prompt = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
prompt.question("Which library? ", function (whichlib) {
"use strict"
var lib = require("./bot-client/lib/" + whichlib),
rules = lib.data.ruleset,
parse = function (ruleset, prefix) {
var key,
str;
for (key in ruleset) {
str += prefix + " - " + key + "\n";
str += (ruleset[key].hasOwnProperty("ruleset"))
? parse(ruleset[key].ruleset, prefix + "\t")
: "";
}
return str;
},
str = parse(rules, "");
console.log("Ready to serve page.");
http.createServer(function (req, res) {
console.log('Server running at http://127.0.0.1:8124/');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(str);
res.end();
}).listen(8124, "127.0.0.1");
});
预期结果示例:
- key1
- key1.1
- key1.1.1
- key1.1.2
- key1.2
- key1.2.1
- key1.2.2
- key1.2.3
- key1.3
- key1.3.1
- key1.3.2
实际结果示例:
undefined - key1
undefined - key1.1
undefined - key1.1.1
- key1.1.2
- key1.2
undefined - key1.2.1
- key1.2.2
- key1.2.3
- key1.3
undefined - key1.3.1
- key1.3.2
问题:
我不明白为什么“未定义”应该出现,更不用说看到它的外观模式了。我错过了一些明显的东西吗?