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?

1

3 Answers 3

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')
})
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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

2 Comments

I don't want to save it as a text file but as an object. I want it to use the least space possible.
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().
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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.