Skip to content

Instantly share code, notes, and snippets.

@Josh4324
Last active November 23, 2020 22:13
Show Gist options
  • Save Josh4324/b220ad04f14b6e3f926b3b7551c594c8 to your computer and use it in GitHub Desktop.
Save Josh4324/b220ad04f14b6e3f926b3b7551c594c8 to your computer and use it in GitHub Desktop.
Create Todo
const fs = require("fs");
const createTodo = (title, todo) => {
try {
// check if the json file exists
fs.access('todos.json', (err) => {
// if it does not exist, create a new json file
if (err){
fs.writeFileSync('todos.json', JSON.stringify([]))
}
// read from the todo.json if it exists
const todoBuffer = fs.readFileSync("todos.json");
// convert it to string
let dataJSON = todoBuffer.toString();
// parse the data
const todos = JSON.parse(dataJSON);
// check if the todo title exists
const duplicateTodo = todos.find((todo) => {
return todo.title === title;
})
if (!duplicateTodo) {
todos.push({
title: title,
todo: todo,
});
dataJSON = JSON.stringify(todos);
fs.writeFileSync("todos.json", dataJSON);
console.log("New Todo Added");
} else {
console.log("New Todo title has already been used");
}
})
}catch(error){
console.log("An error occured, try again")
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment