简体   繁体   中英

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.

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. In Lua, there is unpack() ( Source ), which unpacks a table into separate elements. 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

Try https://github.com/alexei/sprintf.js it supports passing of arrays. For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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