All files / noise-generator/lib electron.js

100% Statements 29/29
100% Branches 6/6
100% Functions 3/3
100% Lines 29/29
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 37 38 39 40      7x 7x   7x   7x 7x 7x 7x 7x 7x 44x 44x 44x 44x 14x 14x 14x 14x 14x 30x 14x 14x 14x 16x 12x 12x 12x   4x 4x 4x          
// TODO: this should be separated into a separate module
'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') {
        const {id, commandId} = params
        files[id].play()
        stdout.write(JSON.stringify({[command]: {id, commandId}}))
      } else if (command === 'loop') {
        const {id, val, commandId} = params
        files[id].loop = val
        stdout.write(JSON.stringify({[command]: {id, val, commandId}}))
      } else {
        const {id, val, commandId} = params
        files[id][command] = val
        stdout.write(JSON.stringify({[command]: {id, val, commandId}}))
      }
    })
  })
}