Soy un poco novato en términos de backend y tengo un 'pequeño' problema con Node.JS. Tengo un sitio creado con el sistema de plantillas handlebars.js y quería lograr un cambio activo de la 'base de datos' escrita en el archivo .json. Tengo una lista de artículos con títulos, etc. y quería escribir un panel muy simple para poder agregar cualquier cosa a esta base de datos. Escribí un script muy simple en node.js, que funciona bien cuando se inicia a través de la consola. Pero quiero poder activarlo simplemente presionando un botón en el lado del cliente.
la parte html es irrelevante, así que digamos que tengo un botón simple
<button id="button1"></button>artículosData.json
{ "articles": [ { "title": "123", "author": "Krzysztof", "category": "Geography", "date": "15-04-2017", "imgsrc": "public/img/office.jpg", "descrSht": "Tym krótkim...", "descr": "Tym krótkim wstepem zaczynam swoj blog", "adress": "poczatek_bloga", "images": { "img1": "public/img/office.jpg" } }, { "title": "asdgsdgsg", "author": "Krzysztof", "category": "History", "date": "12-12-2016", "imgsrc": "public/img/office.jpg", "descrSht": "Tym krótkim...", "descr": "Tym krótkim wstepem zaczynam swoj blog" }, { "title": "asdgsdg", "author": "Krzysztof", "category": "Geography", "date": "15-11-2016", "imgsrc": "public/img/office.jpg", "descrSht": "Tym krótkim...", "descr": "Tym krótkim wstepem zaczynam swoj blog" } ] }y aquí está mi secuencia de comandos node.js que funciona solo a través de la terminal de Windows/Linux
var fs = require('fs'); var fileName = './data/articlesData.json'; var file = require(fileName); var title = "Nowy tytul"; var author = "Krzysztof"; var length = file.articles.length; console.log(length); file.articles[length] = {title: title, author: author}; fs.writeFile(fileName, JSON.stringify(file, null, 2), function (err) { if (err) return console.log(err); console.log(JSON.stringify(file)); console.log('writing to ' + fileName); });Cualquier ayuda sería útil, solo quiero que sea posible activarlo a través del clic del botón. Gracias por adelantado
Intenté usar así:
var file = JSON.parse(fs.readFileSync('./data/articlesData.json'), 'utf8'); file.articles.push({title: title, author: author})