Search code examples
node.jsstreamfilestreamfs

How to save an object in a file using nodejs


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?


Solution

  • 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')
    })