10

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

Ed Williams
  • 2,447
  • 3
  • 15
  • 21

4 Answers4

17

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 }

Community
  • 1
  • 1
Ed Williams
  • 2,447
  • 3
  • 15
  • 21
3

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.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24
1
const fs = require('fs')
const util = require('util')
const obj = {a: 1, b: 2}

fs.writeFileSync(
  './temp.js',
  util.formatWithOptions({compact: false}, 'var obj = %o', obj),
  'utf-8'
)

Formatted output:

// ./temp.js
var obj = {
  a: 1,
  b: 2
}
Emeke Ajeh
  • 933
  • 1
  • 10
  • 16
0

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)
})
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156