简体   繁体   English

什么是在NodeJS中处理语言文件的最佳方法

[英]What would be the best way to handle language files in NodeJS

I am currently working on a website and I want to implement a language file. 我目前正在网站上,我想实现一个语言文件。 Meaning, I want to be able to have a file called language.js, which contains an object of all code-generated strings. 意思是说,我希望能够有一个名为language.js的文件,其中包含所有代码生成的字符串的对象。

An example: 一个例子:

var languageStrings = {
    welcomeMessage: "Welcome to our website, %s!",
    usernameInvalid: "The username '%s' is invalid",
}

module.exports = function(languageString, arguments) {
    // return a parsed string, using arguments
    // so require("./language")("welcomeMessage", "Cyberuben"); should output "Welcome to our website, Cyberuben!"
}

I am unsure how I would be able to achieve this in a fast but functional way. 我不确定如何以快速但实用的方式实现这一目标。 I was planning to use util.format, but this takes every replacement as a single argument, rather than a table or array. 我打算使用util.format,但这将每次替换都作为单个参数,而不是表或数组。 In Lua, there is unpack() ( Source ), which unpacks a table into separate elements. 在Lua中,有unpack()Source ),它将一个表解压缩为单独的元素。 I'm wondering if there is a similar function in JavaScript, or if there are better ways of handling the formatting of an unknown amount of variables to a string 我想知道JavaScript中是否有类似的函数,或者是否有更好的方法来处理未知数量的字符串变量的格式

Try https://github.com/alexei/sprintf.js it supports passing of arrays. 尝试https://github.com/alexei/sprintf.js,它支持数组传递。 For example 例如

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM