Created
September 25, 2019 15:14
-
-
Save pigoz/850b21c7207ac76ad4d568e8c939e5ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const net = require("net"); | |
const crypto = require("crypto"); | |
const process = require("process"); | |
function random() { | |
return crypto.randomBytes(4).readUInt32LE(0); | |
} | |
function connect() { | |
const socket = process.env.SOCKET || "/tmp/mpv.sock"; | |
const s = new net.Socket(); | |
const handlers = {}; | |
function command(x) { | |
const requestId = random(); | |
s.write(JSON.stringify({ command: x, request_id: requestId }) + "\n"); | |
return new Promise(resolve => { | |
handlers[requestId] = resolve; | |
}); | |
} | |
const c = new Promise(resolve => { | |
s.on("data", data => { | |
const json = JSON.parse(data.toString()); | |
if (json.request_id && handlers[json.request_id]) { | |
handlers[json.request_id](json); | |
delete handlers[json.request_id]; | |
} | |
}); | |
s.connect(socket, () => { | |
resolve({ | |
command | |
}); | |
}); | |
}); | |
s.on("close", function() { | |
console.log("Connection closed"); | |
}); | |
return c; | |
} | |
module.exports = { connect }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const connect = require("./mpv").connect; | |
async function main() { | |
const mp = await connect(); | |
const volume = await mp.command(["get_property", "volume"]); | |
console.log(volume); // { data: 100, request_id: 4139289790, error: 'success' } | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment