{"id":16118,"library":"memcache-client","title":"Node.js Memcached Client","description":"memcache-client is a high-performance Node.js client designed for interacting with Memcached servers, focusing on efficient ASCII protocol parsing through direct Node.js Buffer APIs. Originally developed and heavily used at WalmartLabs for powering the walmart.com e-commerce platform, it offers robust features crucial for large-scale applications. These include optional data compression, automatic reconnection on network errors, support for arbitrary Memcached commands, and the ability to store various data types like Buffer, string, numeric, and JSON. The library provides a flexible API supporting both traditional Node.js callbacks and modern Promise-based operations, alongside features like fire-and-forget requests, multiple connections, and TLS support. It is currently at version 1.0.5 and appears to be in a maintenance or stable release state, with a focus on reliability and performance in demanding environments.","status":"active","version":"1.0.5","language":"javascript","source_language":"en","source_url":"https://github.com/electrode-io/memcache","tags":["javascript","memcache","memcached","nodejs","client","ascii","protocol","typescript"],"install":[{"cmd":"npm install memcache-client","lang":"bash","label":"npm"},{"cmd":"yarn add memcache-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add memcache-client","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package is primarily designed for ES Modules. When using CommonJS `require`, access `MemcacheClient` as a named export.","wrong":"const MemcacheClient = require('memcache-client').MemcacheClient;","symbol":"MemcacheClient","correct":"import { MemcacheClient } from 'memcache-client';"},{"note":"This is a TypeScript type helper, essential for correctly typing results from multi-key `get` or `gets` operations to avoid `unknown` types. It's an ESM named export.","wrong":"const { MultiRetrievalResponse } = require('memcache-client');","symbol":"MultiRetrievalResponse","correct":"import { MultiRetrievalResponse } from 'memcache-client';"},{"note":"Methods support both Promise-based and callback-based usage. For reliability, always handle the Promise resolution or callback result.","wrong":"client.set('key', 'data'); // Fire and forget without handling result or error","symbol":"client.set (Promise)","correct":"client.set('key', 'data').then((r) => console.log(r));"}],"quickstart":{"code":"import { MemcacheClient, MultiRetrievalResponse } from 'memcache-client';\nimport assert from 'node:assert';\n\nconst server = 'localhost:11211';\n\n// Create a client with default settings (maxConnections = 1)\nconst client = new MemcacheClient({ server });\n\nasync function runMemcacheExample() {\n  try {\n    // Set a key-value pair using Promises\n    const setResult = await client.set('myKey', 'myValue');\n    assert.deepEqual(setResult, ['STORED']);\n    console.log('Set \"myKey\":', setResult);\n\n    // Get the value of 'myKey' using Promises, with type assertion\n    const getData = await client.get<string>('myKey');\n    assert.equal(getData?.value, 'myValue');\n    console.log('Got \"myKey\":', getData?.value);\n\n    // Set multiple keys concurrently\n    await Promise.all([\n      client.set('key1', 'data1'),\n      client.set('key2', 'data2')\n    ]);\n    console.log('Set \"key1\" and \"key2\".');\n\n    // Get multiple keys with correct TypeScript typing\n    const multiResults = await client.get<MultiRetrievalResponse<string>>(['key1', 'key2']);\n    assert.equal(multiResults['key1'].value, 'data1');\n    assert.equal(multiResults['key2'].value, 'data2');\n    console.log('Got multiple keys:', multiResults);\n\n    // Example with callback for 'delete' (optional pattern)\n    client.delete('myKey', (err, result) => {\n      if (err) {\n        console.error('Delete error:', err);\n      } else {\n        assert.deepEqual(result, ['DELETED']);\n        console.log('Deleted \"myKey\":', result);\n      }\n    });\n  } catch (error) {\n    console.error('An error occurred:', error);\n  } finally {\n    // It's good practice to close connections if not needed anymore, though auto-reconnect handles many cases\n    // client.disconnect(); // (Assuming a disconnect method exists or client handles it internally)\n  }\n}\n\nrunMemcacheExample();","lang":"typescript","description":"This quickstart demonstrates creating a MemcacheClient, setting and retrieving single keys using Promises, concurrently setting multiple keys, and performing a typed multi-key retrieval. It also shows an example of using a callback for deletion."},"warnings":[{"fix":"Install `zstd` on your operating system (e.g., `sudo apt install zstd` on Debian/Ubuntu, `brew install zstd` on macOS) or avoid using the compression option.","message":"Enabling compression features (e.g., `compress: true` in `set` options) requires the `zstd` executable to be installed and available in the system's PATH. If `zstd` is not found, compression will fail, potentially leading to errors or unexpected behavior.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `client.get<MultiRetrievalResponse<YourValueType>>(['key1', 'key2'])` to ensure correct type inference for the returned object.","message":"When retrieving multiple keys using methods like `client.get(['key1', 'key2'])` or `client.gets(['key1', 'key2'])` in TypeScript, it is crucial to apply the `MultiRetrievalResponse` or `MultiCasRetrievalResponse` generic type. Failing to do so will result in `unknown` types for the retrieved values, diminishing type safety.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When creating the client, pass `{ server: 'localhost:11211', ignoreNotStored: true }` in the options object.","message":"By default, the client does not ignore `NOT_STORED` responses from the Memcached server. If integrating with specific Memcached proxy configurations, such as McRouter in AllAsync mode, you might need to instantiate `MemcacheClient` with `{ ignoreNotStored: true }` to prevent these responses from being treated as errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Install the `zstd` command-line utility on your operating system (e.g., `sudo apt install zstd` or `brew install zstd`). Ensure it's accessible in the environment where your Node.js application runs.","cause":"The `zstd` executable is not found in the system's PATH when compression is enabled for data storage.","error":"Error: spawn zstd ENOENT"},{"fix":"For single-key `get`, use a generic: `client.get<string>('key')`. For multi-key `get` or `gets`, use the appropriate type helper: `client.get<MultiRetrievalResponse<string>>(['key1', 'key2'])`.","cause":"Attempting to access properties like `value` on results from `get` or `gets` operations when TypeScript cannot infer the type, typically during multi-key retrievals without using `MultiRetrievalResponse`.","error":"Property 'value' does not exist on type 'unknown'."},{"fix":"If using CommonJS, ensure you're destructuring the named export: `const { MemcacheClient } = require('memcache-client');`. For new projects, it is recommended to use ESM `import { MemcacheClient } from 'memcache-client';` in a `type: \"module\"` Node.js environment.","cause":"This error often occurs when attempting to use CommonJS `require()` to import an ES Module (ESM) package incorrectly, or when the `MemcacheClient` class is not directly exported as a default.","error":"TypeError: MemcacheClient is not a constructor"}],"ecosystem":"npm"}