Search code examples
javascriptelectronsubtitle

How to read and parse srt Subtitle file with Javascript?


I'm trying to make a program that will translate subtiltes file from a given path. The programm is running inside electron - so I have access to the computer's files. The problem is I couldn't find explanation on how to read and parse srt file is it possible?

    function translateSubs(path, newPath){
      var srt = readFile(path)
      var translatedOutput = []
      srt.data.foreach(line => {
        line.text = translateToEnglishline.text()
      })
      parseFile(srt, newPath)
    }

Solution

  • So this is how I did it:

    var { default: srtParser2} = require('srt-parser-2');
    var parser = new srtParser2()
    const fs = require('fs');
    //srt => json
    fs.readFile(path,(err,data) =>{
      if (err) {
        console.error(err);
        return;
      }
      var subObj = parser.fromSrt(data.toString())
      console.log("lines in srt:", subObj.length)
      //json => srt
      outputSrt = ""
      subObj.forEach(item =>{
        translatedSub += "\n" + item.id + "\n"+ item.startTime + " --> " + item.endTime + "\n" + item.text + "\n" 
      })
      fs.writeFile(outputPath, outputSrt, (err) => {console.log(err)})
      console.log("wrote file into path:", outputPath)
    })
    

    Reading srt: First, we read the srt using FS, then we convert the output to string and read it with srt-parser-2 which gives us the srt in JSON

    Creating Srt: we create new string which has this format:

    1
    00:00:11,544 --> 00:00:12,682
    Hello
    
    2
    00:00:17,123 --> 00:00:19,345
    There
    
    3
    00:00:30,123 --> 00:00:31,345
    General Kenobi
    

    then we write it to a file.

    for more information you can see srt-parser-2 docs here: https://www.npmjs.com/package/srt-parser-2