Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript REST APIs with Express Create, Read, Update, Delete Create a New Quote

How does the save function not overwrite the data file?

I'm totally confused about one point here. The createQuote function calls the save function, and looking at save it looks like this should be overwrite the data file it saves to. Here's the function:

function save(data){
  return new Promise((resolve, reject) => {
    fs.writeFile('data.json', JSON.stringify(data, null, 2), (err) => {
      if (err) {
      } else {

According to the node docs, fs.writeFile replaces the file if it writes to an existing file. So why doesn't this over-write? Why aren't we using appendFile?

1 Answer

I think your mindset is right, and what is actually happening, is a new file is created each time we make a save. She is collecting all of the current data, storing it to an array, and then pushing the new record into that array, and passing the entire data set to the save function, thus creating a new file each time, with all of the data including the new record.

I believe this is a form of non-mutation. Do not update the current object. Create a new state object, containing the changes to the data, and return it to the program. As opposed to just updating the existing state object

async function createQuote(newRecord) {
  // Get all current data from file
  const quotes = await getQuotes(); 

  newRecord.id = generateRandomId();
  // Push the new record to the variable we stored our quotes to
  // Pass the entire list of quotes to the save function, including our new quote.
  await save(quotes); 
  return newRecord;