Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save objects to files in Node.js? [duplicate]

I'm running a Node server and I was wondering - how can I serialize objects and write them to a file?

like image 286
corazza Avatar asked Sep 02 '11 14:09

corazza


People also ask

How do I clone a JSON object in node JS?

Object. defineProperty(Object. prototype, 'clone', { enumerable: false, value: function() { var newObj = (this instanceof Array) ? [] : {}; for (i in this) { if (i == 'clone') continue; if (this[i] && typeof this[i] == "object") { newObj[i] = this[i].

How do I copy files from one node js file to another?

copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.

How do I save a file in node JS?

writeFile("/tmp/test", message, function (err) { if (err) { return console. log(err); } console. log("The file was saved!"); }); }); Hope this works for you.


1 Answers

You can use

var str = JSON.stringify(object)

to serialize your objects to a JSON string and

var obj = JSON.parse(string)

To read it back as an object. The string can be written to file. So, for example an object like this:

var p = new Foo();
p.Bar = "Terry"
var s = JSON.stringify(p)
// write s to file, get => { "Bar" : "Terry" }
// read s from file and turn back into an object:
var p = JSON.parse(s);

Writing and reading to/from files is covered here: http://nodejs.org/docs/v0.4.11/api/fs.html#fs.write

like image 149
ConfusedNoob Avatar answered Oct 13 '22 20:10

ConfusedNoob