1

I am programming a strange script that consists of transferring variables from client to a nodejs server.
So if a have a date variable, how can I transfer it and use the same variable on the server?
Is there any way to serialize objects and retrieve them on server side in a way that they remain the same type (date, function, variable, string, object...)?

Thank you

1
  • 1
    Just don't use eval(), whatever you do. Commented Jul 25, 2011 at 18:40

4 Answers 4

2

You can serialize a date by converting it to a number which can be sent via JSON.

new Date(+new Date)

is perfectly valid.

The prefix + in

+new Date

converts the newly created date to a number, and

new Date(myNumber)

reconstitutes a date from a number.

Sign up to request clarification or add additional context in comments.

Comments

1

You might check out DNode in addition to nowjs. I've been watching both of those projects but not dabbled in them yet. However, I get the sense that DNode it is building more traction in the node.js community and I hear praise for it all the time.

https://github.com/substack/dnode http://substack.net/posts/85e1bd/DNode-Asynchronous-Remote-Method-Invocation-for-Node-js-and-the-Browser

Timezones are very important in my application, so I've found that serializing dates to ISO8601 formatted strings for dates works best. @Mike's solution is great if you don't care about timezones, or can assume that all dates are UTC. There are plenty of javascript libraries to help serialize/deserialize ISO8601.

2 Comments

It appears that the now.js project was abandoned several months ago. news.ycombinator.com/item?id=4667826
Is it possible to synchronize variables between the client and the server using dnode?
1

Now.js could abstract all of the serialisation, deserialisation.. it provides a shared namespace between node.js server and browser client:

http://nowjs.com/

Comments

0

As was posted before me, serialize the Date Object to a string literal, either the value in miliseconds or the formatted Date String.

Use a POST request passing the Date string in the request body or a GET requests passing the string via query parameter to get it to the server. There you may deserialize the string using the Date constructor.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.