write a javascript object to a file in node
Thanks Stephan Bijzitter for the link
My problem can be solved like so:
var fs = require('fs')
var util = require('util')
var obj = {a: 1, b: 2}
fs.writeFileSync('./temp.js', 'var obj = ' + util.inspect(obj) , 'utf-8')
This writes a file containing: var obj = { a: 1, b: 2 }
Its because of arguments that writeFile
requires.
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
It wants data to be <String> | <Buffer> | <Uint8Array>
So your first example works because it's a string.
In order to make second work just use JSON.stringify(obj)
;
Like this
fs.writeFile('file.txt', JSON.stringify(obj), callback)
Hope this helps.
You need to stringify your object:
var obj = {a: 1, b: 2}
fs.writeFile('./temp.js', JSON.stringify(obj), function(err) {
if(err) console.log(err)
})