Is it possible to add new content via html input to existing JSON file with fs.writeFile?write/add data in JSON file using node.jsAdd new attribute (element) to JSON object using JavaScriptJavaScript/jQuery to download file via POST with JSON dataHow to send FormData objects with Ajax-requests in jQuery?How to push new key/value pair into external json file?How to get updated json file for new form inputs using javascript or jquery?PHP Handle json sent POST and rewrite existing json with the new oneNode.js: How to write input values of a formular into a JSON file when the submit button is pressed?Without Node.js or running a server, is it possible to create/output a JSON file to hdd through HTML application with pure JavaScript?Adding new object to Json file with jqueryRe-routing to new HTML file within Node.js

Pressure inside an infinite ocean?

Pawn Promotion Double Checks

Besides the up and down quark, what other quarks are present in daily matter around us?

Confused about proofs by contradiction, the Law of the Excluded Middle and existence of consistent axiomatic systems.

Should one double the thirds or the fifth in chords?

Selecting a secure PIN for building access

How to reply this mail from potential PhD professor?

CRT Oscilloscope - part of the plot is missing

Why is B♯ higher than C♭ in 31-ET?

Moving the subject of the sentence into a dangling participle

Was there ever a Kickstart that took advantage of 68020+ instructions that would work on an A2000?

What does a yield inside a yield do?

What happens if I start too many background jobs?

Alias to source .bashrc after it's been edited?

Would "lab meat" be able to feed a much larger global population

For a benzene shown in a skeletal structure, what does a substituent to the center of the ring mean?

Should I replace my bicycle tires if they have not been inflated in multiple years

Can Ghost kill White Walkers or Wights?

What are the differences between credential stuffing and password spraying?

Identifying my late father's D&D stuff found in the attic

Is induction neccessary for proving that every injective mapping of a finite set into itself is a mapping onto itself?

In Avengers 1, why does Thanos need Loki?

How to 'Let Go' in Meditation?

Where can I go to avoid planes overhead?



Is it possible to add new content via html input to existing JSON file with fs.writeFile?


write/add data in JSON file using node.jsAdd new attribute (element) to JSON object using JavaScriptJavaScript/jQuery to download file via POST with JSON dataHow to send FormData objects with Ajax-requests in jQuery?How to push new key/value pair into external json file?How to get updated json file for new form inputs using javascript or jquery?PHP Handle json sent POST and rewrite existing json with the new oneNode.js: How to write input values of a formular into a JSON file when the submit button is pressed?Without Node.js or running a server, is it possible to create/output a JSON file to hdd through HTML application with pure JavaScript?Adding new object to Json file with jqueryRe-routing to new HTML file within Node.js






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm fairly new to node.js! I'm trying to write a comment section that's rendered by node.js server. I have a json file, and I pass its value into an ejs file, so far it renders fine.
Now I added a comment section, with input field and submit button, so my question is:
is it possible to add the input in the comment section back to existing json file, to append new content, then rewrite the json file, then re-render all, after I click the submit button?



I've tried to add event listener to get value, then I try to use JSON.stringfy() to get the string...then I have no clue where to go from now on, because I don't know if the above question is even possible?



In case it's not possible, what should I do to keep my old data, while adding new one and have it render to screen? If database is not involved, then is localStorage my only choice?










share|improve this question






















  • Is there a reason why you are not using a database for storing the comment data?

    – Iskandar Reza Razali
    Mar 22 at 21:35











  • So good to see you asking your first questions. Not sure why you're using JSON files to store your comments list. If you've just started to learn Nodejs then it's ok. I guess this is a duplicate for stackoverflow.com/questions/36856232/…. Although it might work but I don't suggest it at all. A database is what you're seeking. Once you learn how to use one, it's going to be piece of cake. If the link above is not what you're looking for feel free to reply and ask any questions you have :) Best luck on your journey to lean Nodejs

    – mamsoudi
    Mar 22 at 21:57












  • Hi guys, I haven't learnt database yet, so I can't use it. This is a practice project, and our teacher requires us to use what we have to solve the problem.

    – Annie
    Mar 23 at 9:43











  • @Annie can you show us example code/any attempts?

    – Caleb Goodman
    Mar 23 at 17:28











  • Hi all, I'm close to solve all my problems, I will share my answer soon! :D

    – Annie
    Mar 23 at 17:48

















0















I'm fairly new to node.js! I'm trying to write a comment section that's rendered by node.js server. I have a json file, and I pass its value into an ejs file, so far it renders fine.
Now I added a comment section, with input field and submit button, so my question is:
is it possible to add the input in the comment section back to existing json file, to append new content, then rewrite the json file, then re-render all, after I click the submit button?



I've tried to add event listener to get value, then I try to use JSON.stringfy() to get the string...then I have no clue where to go from now on, because I don't know if the above question is even possible?



In case it's not possible, what should I do to keep my old data, while adding new one and have it render to screen? If database is not involved, then is localStorage my only choice?










share|improve this question






















  • Is there a reason why you are not using a database for storing the comment data?

    – Iskandar Reza Razali
    Mar 22 at 21:35











  • So good to see you asking your first questions. Not sure why you're using JSON files to store your comments list. If you've just started to learn Nodejs then it's ok. I guess this is a duplicate for stackoverflow.com/questions/36856232/…. Although it might work but I don't suggest it at all. A database is what you're seeking. Once you learn how to use one, it's going to be piece of cake. If the link above is not what you're looking for feel free to reply and ask any questions you have :) Best luck on your journey to lean Nodejs

    – mamsoudi
    Mar 22 at 21:57












  • Hi guys, I haven't learnt database yet, so I can't use it. This is a practice project, and our teacher requires us to use what we have to solve the problem.

    – Annie
    Mar 23 at 9:43











  • @Annie can you show us example code/any attempts?

    – Caleb Goodman
    Mar 23 at 17:28











  • Hi all, I'm close to solve all my problems, I will share my answer soon! :D

    – Annie
    Mar 23 at 17:48













0












0








0








I'm fairly new to node.js! I'm trying to write a comment section that's rendered by node.js server. I have a json file, and I pass its value into an ejs file, so far it renders fine.
Now I added a comment section, with input field and submit button, so my question is:
is it possible to add the input in the comment section back to existing json file, to append new content, then rewrite the json file, then re-render all, after I click the submit button?



I've tried to add event listener to get value, then I try to use JSON.stringfy() to get the string...then I have no clue where to go from now on, because I don't know if the above question is even possible?



In case it's not possible, what should I do to keep my old data, while adding new one and have it render to screen? If database is not involved, then is localStorage my only choice?










share|improve this question














I'm fairly new to node.js! I'm trying to write a comment section that's rendered by node.js server. I have a json file, and I pass its value into an ejs file, so far it renders fine.
Now I added a comment section, with input field and submit button, so my question is:
is it possible to add the input in the comment section back to existing json file, to append new content, then rewrite the json file, then re-render all, after I click the submit button?



I've tried to add event listener to get value, then I try to use JSON.stringfy() to get the string...then I have no clue where to go from now on, because I don't know if the above question is even possible?



In case it's not possible, what should I do to keep my old data, while adding new one and have it render to screen? If database is not involved, then is localStorage my only choice?







javascript node.js json express ejs






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 21:20









AnnieAnnie

85




85












  • Is there a reason why you are not using a database for storing the comment data?

    – Iskandar Reza Razali
    Mar 22 at 21:35











  • So good to see you asking your first questions. Not sure why you're using JSON files to store your comments list. If you've just started to learn Nodejs then it's ok. I guess this is a duplicate for stackoverflow.com/questions/36856232/…. Although it might work but I don't suggest it at all. A database is what you're seeking. Once you learn how to use one, it's going to be piece of cake. If the link above is not what you're looking for feel free to reply and ask any questions you have :) Best luck on your journey to lean Nodejs

    – mamsoudi
    Mar 22 at 21:57












  • Hi guys, I haven't learnt database yet, so I can't use it. This is a practice project, and our teacher requires us to use what we have to solve the problem.

    – Annie
    Mar 23 at 9:43











  • @Annie can you show us example code/any attempts?

    – Caleb Goodman
    Mar 23 at 17:28











  • Hi all, I'm close to solve all my problems, I will share my answer soon! :D

    – Annie
    Mar 23 at 17:48

















  • Is there a reason why you are not using a database for storing the comment data?

    – Iskandar Reza Razali
    Mar 22 at 21:35











  • So good to see you asking your first questions. Not sure why you're using JSON files to store your comments list. If you've just started to learn Nodejs then it's ok. I guess this is a duplicate for stackoverflow.com/questions/36856232/…. Although it might work but I don't suggest it at all. A database is what you're seeking. Once you learn how to use one, it's going to be piece of cake. If the link above is not what you're looking for feel free to reply and ask any questions you have :) Best luck on your journey to lean Nodejs

    – mamsoudi
    Mar 22 at 21:57












  • Hi guys, I haven't learnt database yet, so I can't use it. This is a practice project, and our teacher requires us to use what we have to solve the problem.

    – Annie
    Mar 23 at 9:43











  • @Annie can you show us example code/any attempts?

    – Caleb Goodman
    Mar 23 at 17:28











  • Hi all, I'm close to solve all my problems, I will share my answer soon! :D

    – Annie
    Mar 23 at 17:48
















Is there a reason why you are not using a database for storing the comment data?

– Iskandar Reza Razali
Mar 22 at 21:35





Is there a reason why you are not using a database for storing the comment data?

– Iskandar Reza Razali
Mar 22 at 21:35













So good to see you asking your first questions. Not sure why you're using JSON files to store your comments list. If you've just started to learn Nodejs then it's ok. I guess this is a duplicate for stackoverflow.com/questions/36856232/…. Although it might work but I don't suggest it at all. A database is what you're seeking. Once you learn how to use one, it's going to be piece of cake. If the link above is not what you're looking for feel free to reply and ask any questions you have :) Best luck on your journey to lean Nodejs

– mamsoudi
Mar 22 at 21:57






So good to see you asking your first questions. Not sure why you're using JSON files to store your comments list. If you've just started to learn Nodejs then it's ok. I guess this is a duplicate for stackoverflow.com/questions/36856232/…. Although it might work but I don't suggest it at all. A database is what you're seeking. Once you learn how to use one, it's going to be piece of cake. If the link above is not what you're looking for feel free to reply and ask any questions you have :) Best luck on your journey to lean Nodejs

– mamsoudi
Mar 22 at 21:57














Hi guys, I haven't learnt database yet, so I can't use it. This is a practice project, and our teacher requires us to use what we have to solve the problem.

– Annie
Mar 23 at 9:43





Hi guys, I haven't learnt database yet, so I can't use it. This is a practice project, and our teacher requires us to use what we have to solve the problem.

– Annie
Mar 23 at 9:43













@Annie can you show us example code/any attempts?

– Caleb Goodman
Mar 23 at 17:28





@Annie can you show us example code/any attempts?

– Caleb Goodman
Mar 23 at 17:28













Hi all, I'm close to solve all my problems, I will share my answer soon! :D

– Annie
Mar 23 at 17:48





Hi all, I'm close to solve all my problems, I will share my answer soon! :D

– Annie
Mar 23 at 17:48












1 Answer
1






active

oldest

votes


















0














now I more or less solve my problem!



Here are how I solved it. Here is my fans.json (sorry, not nice format after I tested it and have it rewritten many times)



"comments":[
"name":"Anna","message":"I love your show last summer in Stockholm! Best summer concert I've been to!",
"name":"Jason","message":"This is War is the best album I've ever bought, I can't get tired of listening to it all the time.",
"name":"Hansel","message":"When are you guys coming to Germany again?","name":"Ash","message":"My favorite song is Up in the Air. It always makes me happy and wanna dance!"]


First I created the template in fans.ejs



<section class="content-section container">
<h2>Dear fans, we'd love to hear from you!</h2>
<% fans.comments.forEach((comment) => %>
<p class="name"><%= comment.name%></p>
<p class="message"><%= comment.message%></p>
<% ) %>

<div id="commentDom">
</div>
</section>

<div class="comment">
<label for="full-name">Name</label>
<input id="full-name" name="full-name" type="text"/>
<label for="message">Comment</label>
<textarea id="message" name="message"></textarea>
<button class="btn btn-primary" value="submit">Submit</button>
</div>


then I wrote this part in this fans.js (there are more to it but I just want to emphasize the part that interacts with server.js



document.querySelector('button').addEventListener('click', (e)=> 
if (name.trim() === '' )


Then I wrote those in the server.js, so the new information gets to be pushed to the my existing fans.json file, then it gets rewritten.



app.post('/fans', (req, res) => 
fs.readFile('fans.json', (error, data)=>
if (error)
res.status(500).end()
else
const fansObj = JSON.parse(data)
fansObj.comments.push(req.body)
fs.writeFile('fans.json', JSON.stringify(fansObj), (error) =>
if (error)
console.log(error)
else
console.log('write successfully!')

)

)
)


After that I found that I have to refresh my page manually to get updated when I clicked the button. I googled around and it seems I have to use websockets or socket.io to solve this problem, which is out of my knowledge scope so far. So I decided to use the simple way by creating two functions, one is to generatedom in my ejs file, which goes in the "commentDom" section, after the original comment section. Another is to remove the input msg in the input area, I remove the msg in the fans.js as well as the ones in the fans.ejs(let them = ''), after the button is clicked, thus we can create a nice immediate feedback to the user. Of course if they refresh the browser, they will be able to see the "real" rendering from the server side.



Of course I know in the real world more things will be involved, such as database etc. I look forward to learning more on that later. :D






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307935%2fis-it-possible-to-add-new-content-via-html-input-to-existing-json-file-with-fs-w%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    now I more or less solve my problem!



    Here are how I solved it. Here is my fans.json (sorry, not nice format after I tested it and have it rewritten many times)



    "comments":[
    "name":"Anna","message":"I love your show last summer in Stockholm! Best summer concert I've been to!",
    "name":"Jason","message":"This is War is the best album I've ever bought, I can't get tired of listening to it all the time.",
    "name":"Hansel","message":"When are you guys coming to Germany again?","name":"Ash","message":"My favorite song is Up in the Air. It always makes me happy and wanna dance!"]


    First I created the template in fans.ejs



    <section class="content-section container">
    <h2>Dear fans, we'd love to hear from you!</h2>
    <% fans.comments.forEach((comment) => %>
    <p class="name"><%= comment.name%></p>
    <p class="message"><%= comment.message%></p>
    <% ) %>

    <div id="commentDom">
    </div>
    </section>

    <div class="comment">
    <label for="full-name">Name</label>
    <input id="full-name" name="full-name" type="text"/>
    <label for="message">Comment</label>
    <textarea id="message" name="message"></textarea>
    <button class="btn btn-primary" value="submit">Submit</button>
    </div>


    then I wrote this part in this fans.js (there are more to it but I just want to emphasize the part that interacts with server.js



    document.querySelector('button').addEventListener('click', (e)=> 
    if (name.trim() === '' )


    Then I wrote those in the server.js, so the new information gets to be pushed to the my existing fans.json file, then it gets rewritten.



    app.post('/fans', (req, res) => 
    fs.readFile('fans.json', (error, data)=>
    if (error)
    res.status(500).end()
    else
    const fansObj = JSON.parse(data)
    fansObj.comments.push(req.body)
    fs.writeFile('fans.json', JSON.stringify(fansObj), (error) =>
    if (error)
    console.log(error)
    else
    console.log('write successfully!')

    )

    )
    )


    After that I found that I have to refresh my page manually to get updated when I clicked the button. I googled around and it seems I have to use websockets or socket.io to solve this problem, which is out of my knowledge scope so far. So I decided to use the simple way by creating two functions, one is to generatedom in my ejs file, which goes in the "commentDom" section, after the original comment section. Another is to remove the input msg in the input area, I remove the msg in the fans.js as well as the ones in the fans.ejs(let them = ''), after the button is clicked, thus we can create a nice immediate feedback to the user. Of course if they refresh the browser, they will be able to see the "real" rendering from the server side.



    Of course I know in the real world more things will be involved, such as database etc. I look forward to learning more on that later. :D






    share|improve this answer



























      0














      now I more or less solve my problem!



      Here are how I solved it. Here is my fans.json (sorry, not nice format after I tested it and have it rewritten many times)



      "comments":[
      "name":"Anna","message":"I love your show last summer in Stockholm! Best summer concert I've been to!",
      "name":"Jason","message":"This is War is the best album I've ever bought, I can't get tired of listening to it all the time.",
      "name":"Hansel","message":"When are you guys coming to Germany again?","name":"Ash","message":"My favorite song is Up in the Air. It always makes me happy and wanna dance!"]


      First I created the template in fans.ejs



      <section class="content-section container">
      <h2>Dear fans, we'd love to hear from you!</h2>
      <% fans.comments.forEach((comment) => %>
      <p class="name"><%= comment.name%></p>
      <p class="message"><%= comment.message%></p>
      <% ) %>

      <div id="commentDom">
      </div>
      </section>

      <div class="comment">
      <label for="full-name">Name</label>
      <input id="full-name" name="full-name" type="text"/>
      <label for="message">Comment</label>
      <textarea id="message" name="message"></textarea>
      <button class="btn btn-primary" value="submit">Submit</button>
      </div>


      then I wrote this part in this fans.js (there are more to it but I just want to emphasize the part that interacts with server.js



      document.querySelector('button').addEventListener('click', (e)=> 
      if (name.trim() === '' )


      Then I wrote those in the server.js, so the new information gets to be pushed to the my existing fans.json file, then it gets rewritten.



      app.post('/fans', (req, res) => 
      fs.readFile('fans.json', (error, data)=>
      if (error)
      res.status(500).end()
      else
      const fansObj = JSON.parse(data)
      fansObj.comments.push(req.body)
      fs.writeFile('fans.json', JSON.stringify(fansObj), (error) =>
      if (error)
      console.log(error)
      else
      console.log('write successfully!')

      )

      )
      )


      After that I found that I have to refresh my page manually to get updated when I clicked the button. I googled around and it seems I have to use websockets or socket.io to solve this problem, which is out of my knowledge scope so far. So I decided to use the simple way by creating two functions, one is to generatedom in my ejs file, which goes in the "commentDom" section, after the original comment section. Another is to remove the input msg in the input area, I remove the msg in the fans.js as well as the ones in the fans.ejs(let them = ''), after the button is clicked, thus we can create a nice immediate feedback to the user. Of course if they refresh the browser, they will be able to see the "real" rendering from the server side.



      Of course I know in the real world more things will be involved, such as database etc. I look forward to learning more on that later. :D






      share|improve this answer

























        0












        0








        0







        now I more or less solve my problem!



        Here are how I solved it. Here is my fans.json (sorry, not nice format after I tested it and have it rewritten many times)



        "comments":[
        "name":"Anna","message":"I love your show last summer in Stockholm! Best summer concert I've been to!",
        "name":"Jason","message":"This is War is the best album I've ever bought, I can't get tired of listening to it all the time.",
        "name":"Hansel","message":"When are you guys coming to Germany again?","name":"Ash","message":"My favorite song is Up in the Air. It always makes me happy and wanna dance!"]


        First I created the template in fans.ejs



        <section class="content-section container">
        <h2>Dear fans, we'd love to hear from you!</h2>
        <% fans.comments.forEach((comment) => %>
        <p class="name"><%= comment.name%></p>
        <p class="message"><%= comment.message%></p>
        <% ) %>

        <div id="commentDom">
        </div>
        </section>

        <div class="comment">
        <label for="full-name">Name</label>
        <input id="full-name" name="full-name" type="text"/>
        <label for="message">Comment</label>
        <textarea id="message" name="message"></textarea>
        <button class="btn btn-primary" value="submit">Submit</button>
        </div>


        then I wrote this part in this fans.js (there are more to it but I just want to emphasize the part that interacts with server.js



        document.querySelector('button').addEventListener('click', (e)=> 
        if (name.trim() === '' )


        Then I wrote those in the server.js, so the new information gets to be pushed to the my existing fans.json file, then it gets rewritten.



        app.post('/fans', (req, res) => 
        fs.readFile('fans.json', (error, data)=>
        if (error)
        res.status(500).end()
        else
        const fansObj = JSON.parse(data)
        fansObj.comments.push(req.body)
        fs.writeFile('fans.json', JSON.stringify(fansObj), (error) =>
        if (error)
        console.log(error)
        else
        console.log('write successfully!')

        )

        )
        )


        After that I found that I have to refresh my page manually to get updated when I clicked the button. I googled around and it seems I have to use websockets or socket.io to solve this problem, which is out of my knowledge scope so far. So I decided to use the simple way by creating two functions, one is to generatedom in my ejs file, which goes in the "commentDom" section, after the original comment section. Another is to remove the input msg in the input area, I remove the msg in the fans.js as well as the ones in the fans.ejs(let them = ''), after the button is clicked, thus we can create a nice immediate feedback to the user. Of course if they refresh the browser, they will be able to see the "real" rendering from the server side.



        Of course I know in the real world more things will be involved, such as database etc. I look forward to learning more on that later. :D






        share|improve this answer













        now I more or less solve my problem!



        Here are how I solved it. Here is my fans.json (sorry, not nice format after I tested it and have it rewritten many times)



        "comments":[
        "name":"Anna","message":"I love your show last summer in Stockholm! Best summer concert I've been to!",
        "name":"Jason","message":"This is War is the best album I've ever bought, I can't get tired of listening to it all the time.",
        "name":"Hansel","message":"When are you guys coming to Germany again?","name":"Ash","message":"My favorite song is Up in the Air. It always makes me happy and wanna dance!"]


        First I created the template in fans.ejs



        <section class="content-section container">
        <h2>Dear fans, we'd love to hear from you!</h2>
        <% fans.comments.forEach((comment) => %>
        <p class="name"><%= comment.name%></p>
        <p class="message"><%= comment.message%></p>
        <% ) %>

        <div id="commentDom">
        </div>
        </section>

        <div class="comment">
        <label for="full-name">Name</label>
        <input id="full-name" name="full-name" type="text"/>
        <label for="message">Comment</label>
        <textarea id="message" name="message"></textarea>
        <button class="btn btn-primary" value="submit">Submit</button>
        </div>


        then I wrote this part in this fans.js (there are more to it but I just want to emphasize the part that interacts with server.js



        document.querySelector('button').addEventListener('click', (e)=> 
        if (name.trim() === '' )


        Then I wrote those in the server.js, so the new information gets to be pushed to the my existing fans.json file, then it gets rewritten.



        app.post('/fans', (req, res) => 
        fs.readFile('fans.json', (error, data)=>
        if (error)
        res.status(500).end()
        else
        const fansObj = JSON.parse(data)
        fansObj.comments.push(req.body)
        fs.writeFile('fans.json', JSON.stringify(fansObj), (error) =>
        if (error)
        console.log(error)
        else
        console.log('write successfully!')

        )

        )
        )


        After that I found that I have to refresh my page manually to get updated when I clicked the button. I googled around and it seems I have to use websockets or socket.io to solve this problem, which is out of my knowledge scope so far. So I decided to use the simple way by creating two functions, one is to generatedom in my ejs file, which goes in the "commentDom" section, after the original comment section. Another is to remove the input msg in the input area, I remove the msg in the fans.js as well as the ones in the fans.ejs(let them = ''), after the button is clicked, thus we can create a nice immediate feedback to the user. Of course if they refresh the browser, they will be able to see the "real" rendering from the server side.



        Of course I know in the real world more things will be involved, such as database etc. I look forward to learning more on that later. :D







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 19:40









        AnnieAnnie

        85




        85





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307935%2fis-it-possible-to-add-new-content-via-html-input-to-existing-json-file-with-fs-w%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현