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

4
  • 3
    JSON.stringify(object) Commented Feb 9, 2017 at 9:11
  • 1
    Possible duplicate of Write objects into file with Node.js Commented Feb 9, 2017 at 9:12
  • search for how to stringify objects! Commented Feb 9, 2017 at 9:15
  • 6
    I don't believe stringify is the answer. This will create a JSON string (i.e. {"a":1,"b":2}) and not a JS object (i.e. {a:1,b:2}) Commented Feb 9, 2017 at 9:48

4 Answers 4

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 }

Sign up to request clarification or add additional context in comments.

1 Comment

This is unfortunately not a proper answer, as util.inspect will truncate arrays and integers, and not result in the expected object.
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.

Comments

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
}

Comments

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

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.