0

I am working on an express.js example app for personal reference. I want to save data, but I do not want to have to set up a database or anything right now.

I was wondering how I would save data to a file in express? It doesn't have to save per se, but I am trying to mimic a database using CRUD and RESTful routing.

Say I have this in data.js

var entries = [
{"id":1, "title":"Hello World!", "body":"This is the body of my blog entry. Sooo exciting.", "published":"01/01/2017"}];


exports.getBlogEntries = function() {
    return entries;
}

exports.getBlogEntry = function(id) {
    for(var i=0; i < entries.length; i++) {
        if(entries[i].id == id) return entries[i];
    }
}

if say getBlogEntries is index, and getBlogEntry would be show, how would I go about mimicking create, update, and destroy? Would the data be persisted or would it save in memory and disappear on page refresh?

James N
  • 523
  • 1
  • 8
  • 30
  • for `create`, just create another object and push it into the array. for destroy, you can either use [splice](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) and read [this](http://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice). `update` should be easy, just find the element and change it. – Aᴍɪʀ Jan 23 '17 at 23:13
  • thanks for the answer @Aᴍɪʀ. would this data be persisted on page refresh? – James N Jan 23 '17 at 23:15
  • as long as server process is running, data is persisted. refreshing the page would not restart the process, so it would be persisted. – Aᴍɪʀ Jan 23 '17 at 23:16

1 Answers1

0

Node is by default single threaded, so you can created an object (or even an array) globally and it will hold the data as long as the program runs. It's also thread safe do operations with it. Just handle it as an static variable in C++.

Cristóvão Trevisan
  • 1,775
  • 17
  • 18