0

I create class in javascript to output config.json

const fs = require('fs');

class config {
    static put(input1,input2) {
        let json = {
            input1 , input2 }
        json = JSON.stringify(json);
        fs.writeFile('./config.json', json, (err) => {
            if (!err) {
                console.log('done');
            }
        });
    }
}

config.put('site_name', 'Blog');       
config.put('maintenance', false);   
config.put('age', 30);                  
config.put('meta', {"description": "lorem ipsum"}); 

will output config.json like this

{"input1":"meta","input2":{"description":"lorem ipsum"}}

i expect to output config.json

{ input1: 'site_name', input2: 'Blog' }
{ input1: 'maintenance', input2: false }
{ input1: 'age', input2: 30 }
{ input1: 'meta', input2: { description: 'lorem ipsum' } }
zedling
  • 638
  • 8
  • 28
okky
  • 137
  • 1
  • 1
  • 7

2 Answers2

1

Use append instead of write

const fs = require('fs');

class config {
    static put(input1,input2) {
        let json = { input1 , input2 };

        json = JSON.stringify(json);

        fs.appendFile('./config.json', json, (err) => {
            if (!err) {
                console.log('done');
            }
        });
    }
} 
zedling
  • 638
  • 8
  • 28
0

Default options flag for writeFile is 'w' which will overwrite, you will need to specify 'a' for appending.

See here: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback and here for the file system flags: https://nodejs.org/api/fs.html#fs_file_system_flags

Stephan Wiehr
  • 166
  • 1
  • 7