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' } }
3
  • 3
    aren't you overwriting the file each time instead of appending into it? Commented May 29, 2018 at 7:31
  • Possible duplicate of How to append to a file in Node? Commented May 29, 2018 at 7:34
  • Why do you call the file config.json when you don't store JSON in it? Commented May 29, 2018 at 7:35

2 Answers 2

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');
            }
        });
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

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

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.