gpt4 book ai didi

javascript - 从 fs 目录中动态嵌套结果到对象中

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:24 24 4
gpt4 key购买 nike

读取文件目录中的一堆翻译文件并将数据分配给全局对象,以便我可以使用 i18nContent.messages.en.9999 提取翻译

文件树是这样的

locales
messages
en.json => {"9999": "Unexpected Error", "0": "Success"}
de.json => {"9999": "German Error", "0": "German Success"}
emails
en.json => {"signupEmail": "Thanks for signing up", "passwordEmail": "Password changed"}
de.json => {"signupEmail": "German signing up", "passwordEmail": "German Password changed"}

我能够获取每个嵌套对象的所有“名称”。但是,我无法在目录遍历期间组装整个对象。

尝试 1

global.i18nContent = {};

walkDir(dir, function (filePath, dir) {
if (filePath.substr(-5) === ".json") {
let directory = dir.split(/[\s\/]+/);
directory = directory[directory.length - 1];

let lang = filePath.split(/[\s\/]+/);
lang = lang[lang.length - 1].substr(-7, 2);

//this substr fix is to make this work on Macs
let rem = __dirname.toString().substr(0, __dirname.toString().length - 3);

let langFolder = {};
langFolder[lang] = require(filePath.replace(rem, '../'));

Object.assign(i18nContent[directory], langFolder);
}
});

尝试2

已删除

let langFolder = {};
langFolder[lang] = require(filePath.replace(rem, '../'));

Object.assign(i18nContent[directory], langFolder);

并且刚刚尝试了 i18nContent[directory][lang] = require(filePath.replace(rem, '../'))i18nContent[directory[lang]] = require(filePath.replace(rem, '../'))

控制台输出显示['undefined']

应嵌套引用,如 i18nContent.messages.en.9999

最佳答案

我假设您正在使用 walkdir , 正确的?然后我就这样做:

global.i18nContent = {};
const emitter = walkDir(yourDir);

emitter.on('file', filename => {
const parts = filename.match(/^.*\/locales\/(\w*)\/(\w*)\.json$/);

if (!parts) return;
const [, folderName, lang] = parts;

if (!global.i18nContent[folderName]) global.i18nContent[folderName] = {};
global.i18nContent[folderName][lang] = require(filename);
});

关于javascript - 从 fs 目录中动态嵌套结果到对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54431219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com