Home > Web Front-end > JS Tutorial > Building a Simple Redis Store with Node.js

Building a Simple Redis Store with Node.js

DDD
Release: 2024-10-22 06:22:30
Original
812 people have browsed it

Building a Simple Redis Store with Node.js

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');
});
Copy after login

? 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 or netcat, and see your commands in action!

? To Try It Out:

  1. Save the code as simpleRedis.js.
  2. Run it with node simpleRedis.js.
  3. Open a new terminal and connect to it using:
   telnet localhost 3001
Copy after login
  1. Now, you can interact with your in-memory key-value store!

For example:

SET name Hoang
GET name
>> Hoang
DELETE name
GET name
>> NULL
Copy after login

Github
Give it a try! ? Let me know what you think or how you'd extend this.


The above is the detailed content of Building a Simple Redis Store with Node.js. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template