const net = require('net');
class SimpleRedisClient {
constructor(host = 'localhost', port = 7379) {
this.host = host;
this.port = port;
this.socket = null;
this.connected = false;
}
connect() {
return new Promise((resolve, reject) => {
this.socket = new net.Socket();
this.socket.setTimeout(5000);
this.socket.on('connect', () => {
this.connected = true;
resolve(true);
});
this.socket.on('error', (err) => {
reject(err);
});
this.socket.on('timeout', () => {
reject(new Error('Connection timeout'));
});
this.socket.connect(this.port, this.host);
});
}
disconnect() {
if (this.socket) {
this.socket.destroy();
this.socket = null;
this.connected = false;
}
}
sendCommand(...args) {
return new Promise((resolve, reject) => {
if (!this.connected) {
reject(new Error('Not connected'));
return;
}
let command = `*${args.length}\r\n`;
for (const arg of args) {
const argStr = String(arg);
command += `$${argStr.length}\r\n${argStr}\r\n`;
}
let responseData = '';
const responseHandler = (data) => {
responseData += data.toString();
if (responseData.includes('\r\n')) {
this.socket.removeListener('data', responseHandler);
resolve(this._parseResponse(responseData));
}
};
this.socket.on('data', responseHandler);
this.socket.write(command);
});
}
_parseResponse(responseStr) {
const trimmed = responseStr.trim();
if (trimmed.startsWith('+')) {
return trimmed.substring(1);
} else if (trimmed.startsWith(':')) {
return parseInt(trimmed.substring(1));
} else if (trimmed.startsWith('$')) {
const lines = trimmed.split('\r\n');
if (lines[0] === '$-1') {
return null; }
const length = parseInt(lines[0].substring(1));
return lines[1] || '';
} else if (trimmed.startsWith('-')) {
return trimmed.substring(1);
} else if (trimmed.startsWith('*')) {
return trimmed;
} else {
return trimmed;
}
}
}
async function main() {
console.log('🔥 Simple Ignix Node.js Client Example');
console.log('=' .repeat(45));
const client = new SimpleRedisClient();
try {
console.log('Connecting to Ignix server at localhost:7379...');
await client.connect();
console.log('✅ Connected successfully!');
console.log('\n🏓 Testing Connection:');
console.log('-'.repeat(20));
const pingResponse = await client.sendCommand('PING');
console.log(`PING response: ${pingResponse}`);
console.log('\n📝 Basic Operations:');
console.log('-'.repeat(20));
const setResponse = await client.sendCommand('SET', 'hello', 'world');
console.log(`✅ SET hello world: ${setResponse}`);
const getResponse = await client.sendCommand('GET', 'hello');
console.log(`✅ GET hello: ${getResponse}`);
const existsResponse = await client.sendCommand('EXISTS', 'hello');
console.log(`✅ EXISTS hello: ${existsResponse}`);
console.log('\n🔢 Counter Operations:');
console.log('-'.repeat(25));
await client.sendCommand('SET', 'counter', '0');
for (let i = 0; i < 3; i++) {
const incrResponse = await client.sendCommand('INCR', 'counter');
console.log(`✅ INCR counter: ${incrResponse}`);
}
console.log('\n🗂️ Multiple Operations:');
console.log('-'.repeat(25));
const msetResponse = await client.sendCommand('MSET', 'fruit1', 'apple', 'fruit2', 'banana');
console.log(`✅ MSET fruit1=apple fruit2=banana: ${msetResponse}`);
const mgetResponse = await client.sendCommand('MGET', 'fruit1', 'fruit2');
console.log(`✅ MGET fruit1 fruit2: ${mgetResponse}`);
console.log('\n🔄 Key Management:');
console.log('-'.repeat(20));
const renameResponse = await client.sendCommand('RENAME', 'hello', 'greeting');
console.log(`✅ RENAME hello -> greeting: ${renameResponse}`);
const greetingResponse = await client.sendCommand('GET', 'greeting');
console.log(`✅ GET greeting: ${greetingResponse}`);
const oldExistsResponse = await client.sendCommand('EXISTS', 'hello');
console.log(`✅ EXISTS hello (should be 0): ${oldExistsResponse}`);
const delResponse = await client.sendCommand('DEL', 'greeting');
console.log(`✅ DEL greeting: ${delResponse}`);
console.log('\n✅ All operations completed successfully!');
} catch (error) {
if (error.code === 'ECONNREFUSED') {
console.error('❌ Connection Error: Could not connect to Ignix server');
console.error('Make sure Ignix server is running: cargo run --release');
} else {
console.error('❌ Error:', error.message);
}
process.exit(1);
} finally {
client.disconnect();
console.log('\n🔌 Disconnected from server');
}
}
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
main().catch(console.error);