0

我是 JS 和 Node.js 的新手,我正在开发一个使用 Azure Translator API 翻译 webVTT 字幕文件的个人项目 - 为此,我使用 node-webvtt npm 包来解析/编译 webVTT 文件。解析操作提供了一个 JSON 对象,其中包含一个包含数千个提示的数组,如下所示:

[
      {
         "identifier":"",
         "start":60,
         "end":61,
         "text":"My text to be translated #1",
         "styles":""
      },
      {
         "identifier":"",
         "start":110,
         "end":111,
         "text":"My text to be translated #2",
         "styles":""
      }
]

为了翻译“文本”属性,我使用了Microsoft 在 GitHub 上提供的代码示例,并将以下更改应用于 translateText 函数:

  • 我创建了一个返回“提示”对象的承诺(不仅是翻译的文本)
  • 我将“提示”对象作为输入和要翻译的语言

然后我按照这里提供的代码,使用 Promise.all 和 item.map 的组合通过我的异步 translateText 函数翻译所有提示文本

这是我的 index.js 的代码 - 它可以工作,但我不太喜欢这段代码,我相信它可以优化并且看起来更好。

require('dotenv').config();
const { readFileSync, writeFileSync } = require('fs');
const { parse, compile }  = require('node-webvtt');
const { translateText } = require('./translate.js');

const inputStr = readFileSync('./subtitles.vtt', 'utf8');
const webVTT = parse(inputStr, { meta: true, strict : true });

const MSTranslateAsync = async (cue) => {
  return translateText(cue, 'fr')
}

const mapAsync = async (vttCues) => {
  return Promise.all(vttCues.map(cue => MSTranslateAsync(cue)))
}
    
mapAsync(webVTT.cues)
  .then(() => {
    outStr = compile(webVTT);
    writeFileSync('./translated_fr.vtt', outStr, 'utf8');
  });

例如,我正在寻找一种仅使用 Promises 并获得您的建议以优化此代码的方法

mapAsync(webVTT.cues)
      .then(compile(webVTT))
      .then((data) => writeFileSync('./translated_fr.vtt', data, 'utf8'));
4

1 回答 1

0
// not required but I'm using async version of fs in my projects
const fsAsync = require('fs').promises;
//
const compileAndWrite = async ()=>{
    await mapAsync(webVTT.cues);
    let outStr = compile(webVTT); //let outStr = await compile(webVTT);
    await fsAsync.writeFile('./translated_fr.vtt', outStr, 'utf8'); // ou use writeFileSync() 
};

compileAndWrite();
于 2020-10-05T09:15:42.037 回答