i18n_csv_loader.js 914 B

12345678910111213141516171819202122232425262728293031323334
  1. const Readable = require("stream").Readable;
  2. const csv = require("csv-parser");
  3. function createStream (text) {
  4. const stream = new Readable();
  5. stream.push(text);
  6. stream.push(null);
  7. return stream;
  8. }
  9. module.exports = function (csv_data) {
  10. const callback = this.async();
  11. let csv_headers = [];
  12. const file_data = []
  13. const stream = createStream(csv_data);
  14. stream.pipe(csv())
  15. .on('error', error => callback(error))
  16. .on('headers', headers => csv_headers = headers)
  17. .on('data', data => file_data.push(data))
  18. .on('end', () => {
  19. const id = csv_headers[0];
  20. const messages = {};
  21. for(let i = 1; i < csv_headers.length; i += 1) {
  22. const lang = csv_headers[i];
  23. const strings = {};
  24. file_data.forEach( data => {
  25. strings[data[id]] = data[lang];
  26. });
  27. messages[lang] = strings;
  28. }
  29. callback(null, `module.exports = ${JSON.stringify(messages)}`);
  30. })
  31. }