Ash
Ash

Reputation: 896

Automatically export strings for internationalization in Node.js

If I am using an npm module such as i18n, the keys are stored in language specific files such as locale/en.js or locale/de.js:

en.js
{
  "hello world": "hello world"
}

Is there a tool to export strings using their format, e.g. _("Hello world"), and automatically insert them into the langauge files as is for en.js, and for other language files an empty string, e.g. "new key": "" to take out some of the leg work of having to add them while coding all the time.

As an example: If I add a new string _("some str"), a new key "some str": "some str" will be added to en.js and "some str": "" to de.js upon running the tool.

Upvotes: 0

Views: 260

Answers (1)

Prasanna
Prasanna

Reputation: 4656

If you just want the object, you can use fs to save it to a js file or a json file.

test.js

var fs = require('fs')
try {
  var en = JSON.parse(fs.readFileSync('en.js'))
  var de = JSON.parse(fs.readFileSync('de.js'))
} catch(err) {
  // no file present
  en = {};
  de = {};
}
var string = process.env.string;
en[string] = string;
de[string] = "";
console.log(JSON.stringify(en), JSON.stringify(de))
fs.writeFile('en.js', JSON.stringify(en))
fs.writeFile('de.js', JSON.stringify(de))

And as you can see, the string variable is just a env parameter.

string=hello node test.js

Or you can just save them to a json file

fs.writeFile('en.json', JSON.stringify(en))
fs.writeFile('de.json', JSON.stringify(de))

Be careful if you are using this script along with the script that is consuming the object. As writeFile is an async operation

Upvotes: 1

Related Questions