3

My code is this:

fs.writeFile("file.bin", this, 'binary', function(err){
  if(err) console.log(err);
  else console.log("file saved");
});

This is inside a function with a bunch of attributes. If I do console.log(this), it shows the object but when I save it, the file has only this:

[object Object]

Since I didn't get the answer I wanted, I want to clarify a bit what I want. I want my object to be stored as an object but not as a json file or txt file. If I have a mp3 stream for example, I want this stream to be stored as a mp3 file not a json file. Someone knows how to do this?

Sacha Charbit
  • 363
  • 1
  • 3
  • 10
  • check out this question first http://stackoverflow.com/questions/21976567/write-objects-into-file-with-node-js – AIon Mar 31 '17 at 21:17

3 Answers3

7

From the Node documentation for FileSystem, the second parameter needs to be a string, buffer or UintArray. To persist the object to the file, convert the object to a string using JSON.stringify(obj) and call the fs.writeFile() API.

Here is the code snippet for the same:

fs.writeFile("file.bin", JSON.stringify(obj), 'binary', (err)=>{
   if(err) console.log(err)
   else console.log('File saved')
})

Another way is to use a buffer in place of the string.

var buffer = Buffer.from(JSON.stringify(obj))
fs.writeFile("file.bin", buffer, 'binary', (err)=>{
   if(err) console.log(err)
   else console.log('File saved')
})
srm912
  • 86
  • 1
  • Is the data stored as a string or as an object as a result of this? Also, what is the quickest? The string or the buffer? – Sacha Charbit Apr 01 '17 at 05:13
0

You can't save it as an object to a file, but you can save it as a textual representation of an object. You need to turn the object into a string using JSON.stringify. Like this:

var myObj = {a:123,b:456};
JSON.stringify(myObj);

or in your case:

JSON.stringify(this);

Then when you need to access it, you can turn it back into an object with JSON.parse()

References

JSON.stringify

JSON.parse

fredrover
  • 2,997
  • 2
  • 17
  • 24
  • I don't want to save it as a text file but as an object. I want it to use the least space possible. – Sacha Charbit Mar 31 '17 at 20:55
  • You can't save it as an object to a file, but you can save it as a textual representation of an object. Then when you need to access it, you can turn it back into an object with `JSON.parse()`. – fredrover Mar 31 '17 at 21:20
0

Of course you can save an object to a file, what do you think pictures are?

Consider something like:

  const fd = fs.openSync('myFile.bin', 'w')
  fs.writeSync(fd, Buffer.from(myObject, 'base64'))
ostergaard
  • 3,377
  • 2
  • 30
  • 40