Skip to content

Instantly share code, notes, and snippets.

@micalevisk
Last active January 17, 2022 01:26
Show Gist options
  • Save micalevisk/eabef02f09df59ee2feae4395a3aa407 to your computer and use it in GitHub Desktop.
Save micalevisk/eabef02f09df59ee2feae4395a3aa407 to your computer and use it in GitHub Desktop.
NodeJS slim function to generate a string that follows the Redis protocol (RESP) from a command name and its args. Inspired by https://redis.io/topics/mass-insert
// https://redis.io/topics/protocol
/**
* @param {string} str
* @returns {number}
* (c) https://stackoverflow.com/a/27377098/5290447
*/
function getBinarySize(str) {
return Buffer.byteLength(str, 'utf8');
}
function generateRedisProtocolVersion(cmd, ...args) {
return [
"*" + cmd.length,
].concat(
(args || []).map(arg => ["$" + getBinarySize(arg), arg]).flat()
)
.join("\r\n")
}
console.log(
generateRedisProtocolVersion("SET", "key", "value")
/*
*3<cr><lf>
$3<cr><lf>
SET<cr><lf>
$3<cr><lf>
key<cr><lf>
$5<cr><lf>
value<cr><lf>
*/
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment