Juri Bojka
Juri Bojka

Reputation: 415

Get memcache data from php in nodejs


I have problem with get data from memcache in nodejs. First of all i set data in memcache with php Php code:

$memcache = new Memcache;<br>
  $memcache->connect("localhost",11211);<br>
  $array = array("id"=>"1","name"=>"aaa");<br>
  $memcache->set("key",$array);

After this i check if this data is set in memcache and it show:
a:2:{s:2:"id";s:1:"1";s:4:"name";s:3:"aa a";}
Everything seems to be okay. Now i want to get this data in nodejs:
Nodejs code:

var memcache = require('mem');
var client = new memcache.Client(11211,'localhost');
client.connect();
client.get('key', function(err,result){ 
console.log(result);
});

And here i have problem...In console i get

a:2:{s:2:"id";s:1:"1";s:4:"name";s:3:"aa a";}

And my Question is How to get in console name : aaa ? I only add that:

console.log(result['name']); => show : undefined

Please help

Upvotes: 0

Views: 1202

Answers (2)

button
button

Reputation: 656

Try using a more portable format to share data between the systems. E.g. JSON.

$memcache = new Memcache;
$memcache->connect("localhost",11211);
$data = json_encode(array("id"=>"1","name"=>"aaa"));
$memcache->set("key",$data);

I expect this to then show in memcache as

{ "id" : 1, "name": "aaa" }

Then you should be able to extract it as JSON:

var memcache = require('mem');
var client = new memcache.Client(11211,'localhost');
client.connect();
client.get('key', function(err,result){ 
    console.log(result);
    var entry = JSON.parse(result);
    console.log(entry.name);
});

Upvotes: 1

cwurtz
cwurtz

Reputation: 3257

The PHP data looks likes it's being automatically serialized for you.

Instead of letting that happen, I would suggest you encode your array into JSON data prior to inserting into memcache, which you can easily decode with node.

So instead of

$memcache->set("key",$array);

do:

$memcache->set("key", json_encode($array));

And then in node, instead of:

client.get('key', function(err,result){ 
    console.log(result);
});

do:

client.get('key', function(err,result){ 
    var object = JSON.parse(result);
    console.log(object);
    console.log(object['name']);
});

Which will load that data into a JS object.

Upvotes: 1

Related Questions