Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a javascript object to a file in node

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

like image 664
Ed Williams Avatar asked Feb 09 '17 09:02

Ed Williams


People also ask

Can JavaScript write to a file?

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.

Which method is used to write a file in node JS?

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.


4 Answers

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 }

like image 121
Ed Williams Avatar answered Sep 26 '22 21:09

Ed Williams


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.

like image 35
Mykola Borysyuk Avatar answered Sep 30 '22 21:09

Mykola Borysyuk


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)
})
like image 36
Robby Cornelissen Avatar answered Sep 28 '22 21:09

Robby Cornelissen


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]
})
like image 30
Pbd Avatar answered Sep 27 '22 21:09

Pbd