Last active
January 17, 2022 01:26
-
-
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
This file contains hidden or 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
// 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