Reputation: 11
I am trying to program a recipe website in JavaScript. The recipe editor is able to load in contents from a JSON file by creating HTML elements to store them. I want it to be able to then construct a string literal from the data as it is changed by the user, and write it back to the JSON file.
The file's path is "/JS_Scripts/Recipes/JSON/test.json"
function writeToRecipeFile(filePath)
{
let formData = new FormData();
let recipeFileContents =
`{
"image": "",
"title": "${document.getElementById("titleInput").value}",
"description": "${document.getElementById("descriptionInput").innerText}",
"ingredients": [`
//Add ingredients array
for(i = 1; i <= ingredientCount; i++)
{
recipeFileContents = recipeFileContents +
`[
"${document.getElementById("ingredientType"+i).value}",
${document.getElementById("ingredientAmount"+i).value},
"${document.getElementById("ingredientMeasurement"+i)}"
]`
if(i < ingredientCount)
{
recipeFileContents = recipeFileContents +
`,
`;
}
}
recipeFileContents +=
` ],
"steps": [
`;
//Add all steps
for(i = 1; i < stepCount; i++)
{
recipeFileContents +=
`"${document.getElementById("stepInput"+i).innerText}",
`
}
//Add info
recipeFileContents +=
` ],
"info": [ ${document.getElementById("prep-time-hr").value},
${document.getElementById("prep-time-min").value},
${document.getElementById("servings").value},
${document.getElemenyById("serving-size").value},
"${document.getElementById("prep-time-hr").value}" ]`;
// End of JSON contents. Put a fork in it, it's done!
recipeFileContents +=
` ]
}
`
//FIXME: This is where I need to write recipeFileContents to test.json
}
I tried using
const fs = require('fs');
fs.writeFile(filepath, recipeFileContents, (err) => {
if(err) throw err;
})
but it said "require is not defined" in the console.
Upvotes: 0
Views: 106