Wednesday 26 April 2017

Using simple scripts written in Node JS by invoking in HTML

I'm kinda newbie in terms of any backend and have a 'little' problem with Node.JS. I have a site built with handlebars.js templates system, and wanted to achieve active changing of 'data base' written in .json file. I have a list of articles with titles etc. and wanted to wrote a very simple panel to be able to add anything to this database. I wrote a very simple script in node.js, which works fine when launching through console. But I want to be able to activate it through simple push of button on client side.

html part is irrelevant, so let's say i have simple button

<button id="button1"></button>

articlesData.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"
    }
  ]
}

and here is my node.js script which works through windows/linux terminal only

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);
});

Any help would be useful, I only want to make it possible to activate it through button click. Thanks in advance



via Krzysiek Wąsowicz

No comments:

Post a Comment