All files / node-play-mp3/lib electron.js

100% Statements 27/27
100% Branches 8/8
100% Functions 3/3
100% Lines 26/26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36    11x 11x   11x   11x 11x 11x 11x 11x 11x 23x 23x 23x 23x 11x 11x 11x 11x 11x 12x 3x 3x 3x   9x 9x 9x 9x          
'use strict'
 
const fs = require('fs')
const JSONStream = require('JSONStream')
 
const audioUriPrefix = 'data:audio/mp3;base64,'
 
module.exports = function (data) {
  let files = {}
  const { stdin, stdout } = require('electron').remote.process
  const objects = JSONStream.parse()
  stdin.pipe(objects)
  objects.on('data', (d) => {
    const data = d
    Object.keys(data).forEach(command => {
      const params = data[command]
      if (command === 'open') {
        const {id, path} = params
        const blob = fs.readFileSync(path)
        const base64 = Buffer.from(blob).toString('base64')
        const uri = audioUriPrefix + base64
        files[id] = new Audio(uri)
      } else if (command === 'play' || command === 'stop') {
        const {id, commandId} = params
        files[id][command]()
        stdout.write(JSON.stringify({[command]: {commandId}}))
      } else {
        const {id, val, commandId} = params
        if (typeof val !== 'undefined') files[id][command] = val
        const currentVal = files[id][command]
        stdout.write(JSON.stringify({[command]: {val: currentVal, commandId}}))
      }
    })
  })
}