node.js - 读取文件夹中的所有 JSON 并获取它们的字符串
问题描述
有一个包含很多 JSON 文件的文件夹,它们都有一个名为"name"
I want to get their strings and turn them into a string like this的对象
name0=UsernameExample;name1=Flowers;name2=Test; ...
name 后面的数字是 json 的索引/计数,例如它的 name48,它是第 48 个 json 到目前为止,我只尝试从文件夹中读取 JSON,但我当然失败了
let s = "";
fs.readdir('/tmp/userdb/', (files) => {
files.each(file => {
name = file[file.keys()[0]];
})})
我已经可以转换这个
var other_users = (serialize({
"sid0": 0,
"name0": "user1",
"pays0": "8521",
"avatar0": "357",
"onlinescore0": "50"
}));
对此:
sid0=0;name0=user1;pays0=8521;avatar0=357;onlinescore0=50
有了这个常量
const serialize = obj =>
Object.entries(obj).map(([k, v]) => `${k}=${v}`).join(';')
我想用这种方式将结果发送给用户
if (req.query.d === 'getRandomPlayers') {
var sessionid = req.body.player_sid
let user = require("./tmp/userdb/" + sessionid + ".json")
var current_user = (serialize({
player_name: user.name
}));
res.send("method_id=1665;" + current_user);
}
这应该res.send("method_id=1665;" + current_user + thefinalresult);
thefinalresult
是这一切都应该去的。current_user
和其他东西与这个问题无关。
解决方案
假设里面的示例JSON
文件/tmp/userdb/
具有以下结构,
{
"53874745": {
"avatar": "372",
"name": "BILLY",
"onlinescore": "1",
"pays": "8758"
}
}
您可以执行以下操作:
const { promisify } = require("util");
const fs = require("fs");
const path = require("path");
const readdir = promisify(fs.readdir);
const readFile = promisify(fs.readFile);
async function process(excludedSessionId) {
try {
const entries = [];
// get a list of all `JSON` files
const jsonFiles = await readdir(
path.join(__dirname, "./tmp/userdb/")
).then(
(files) => files.filter(
(file) => path.extname(file) === ".json" && !file.includes(excludedSessionId)
)
);
// iterate through a list of all `JSON` files & read their content
for (const [index, file] of jsonFiles.entries()) {
const content = await readFile(
path.join(__dirname, "./tmp/userdb/", file)
).then(JSON.parse);
// create an object for a new entry
const key = `sid${index}`;
const keyValue = Object.keys(content)[0];
// use the `spread syntax` to include the rest of the
// properties in a new entry
const entry = {
[key]: keyValue,
...content[keyValue],
};
entries.push(entry);
}
console.log(entries[0]);
// {
// sid0: '53874745',
// avatar: '372',
// name: 'BILLY',
// onlinescore: '1',
// pays: '8758'
// }
const result = entries.map((entry) => serialize(entry)).join(";");
console.log(result);
// sid0=53874745;avatar=372;name=BILLY;onlinescore=1;pays=8758;
// sid1=154261758;avatar=480;name=JESSEY;onlinescore=30;pays=8521;
return result;
} catch (error) {
console.error(error);
throw error;
}
}
process("154261742");
然后,如果您想在路由控制器的回调中使用此函数,您可以执行以下操作:
app.get("/user", (req, res) => {
// ...
const excludedSessionId = req.body.player_sid;
process(excludedSessionId)
.then(result => {
res.send(result);
})
.catch(error => {
res.status(500).send("Something went wrong.");
});
});
参考:
推荐阅读
- android - 为什么 ConstraintLayout 中的 Barrier 行为如此奇怪?
- javascript - 检查谷歌分析 IP 匿名化的集成
- forms - Xamarin Forms 中的 PopAsync 后 UWP AdControl 空白
- c# - 转换枚举?诠释?使用反射时失败
- sql-server - 尽管有索引,查询仍需要很长时间
- json - ArrayField 与 JSONField 作为 Django 中的 base_field
- angular - Angular4背景图片
- java - 为了访问java中其他地方的数据,我应该把它放在哪里?
- sharedpreferences - 如何将 CheckBoxPreference 键调用到 SettingsPreferences.java 文件
- c - 布林带中的分段错误