How do I use Node to take a JS object (e.g. var obj = {a: 1, b: 2}
) and create a file that contains that object?
For example, the following works:
var fs = require('fs')
fs.writeFile('./temp.js', 'var obj = {a: 1, b: 2}', function(err) {
if(err) console.log(err)
// creates a file containing: var obj = {a: 1, b: 2}
})
But this doesn't work:
var obj = {a: 1, b: 2}
fs.writeFile('./temp.js', obj, function(err) {
if(err) console.log(err)
// creates a file containing: [object Object]
})
Update: JSON.stringify()
will create a JSON object (i.e. {"a":1,"b":2}
) and not a Javascript object (i.e. {a:1,b:2}
)
There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs. js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system.
writeFile() Method. The fs. writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists.
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)
})
Use JSON.stringify()
var obj = {a: 1, b: 2}
fs.writeFile('./temp.js', JSON.stringify(obj), function(err) {
if(err) console.log(err)
// creates a file containing: [object Object]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With