Hey buddies! 👋
I’ve been playing around with Node.js and decided to create a lightweight in-memory key-value store that mimics a simple version of Redis. If you're looking to get started with networking in Node.js, or just love exploring fun side projects, this one’s for you!
🔑 Key Features:
-
Commands Supported:
-
SET key value
- Store key-value pairs. -
GET key
- Retrieve the value of a key. -
DELETE key
- Remove a key-value pair.
-
- Uses Node.js's
net
module to create a TCP server for handling client connections. - A really simple redis store, great for quick tests or learning TCP interactions!
⚙️ Code Overview:
const net = require('net');
class SimpleRedis {
constructor() {
this.store = {};
}
set(key, value) {
this.store[key] = value;
}
get(key) {
return this.store[key] || null;
}
delete(key) {
delete this.store[key];
}
}
// Initialize store
const store = new SimpleRedis();
// Create a TCP server
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
const command = data.toString().trim().split(' ');
const action = command[0].toUpperCase();
let response = '';
switch (action) {
case 'SET':
const [key, value] = command.slice(1);
store.set(key, value);
response = `>> OK\n`;
break;
case 'GET':
const keyToGet = command[1];
const result = store.get(keyToGet);
response = result ? `>> ${result}\n` : '>> NULL\n';
break;
case 'DELETE':
const keyToDelete = command[1];
store.delete(keyToDelete);
response = `>> OK\n`;
break;
default:
response = '>> Invalid command\n';
}
// Send the response with '>>'
socket.write(response);
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
// Start the server on port 3001
server.listen(3001, () => {
console.log('Server is running on port 3001');
});
💡 What’s Happening:
- The server listens on port
3001
and responds to SET, GET, and DELETE commands. - It’s super simple and straightforward—just send a command from any TCP client like
telnet
ornetcat
, and see your commands in action!
💻 To Try It Out:
- Save the code as
simpleRedis.js
. - Run it with
node simpleRedis.js
. - Open a new terminal and connect to it using:
telnet localhost 3001
- Now, you can interact with your in-memory key-value store!
For example:
SET name Hoang
GET name
>> Hoang
DELETE name
GET name
>> NULL
Github
Give it a try! 😎 Let me know what you think or how you'd extend this.
Top comments (2)
Hello everyone! 👋 I am a developer and just want to bring more value. Let me know what you want to build with javascript. I will try
Awesome!