user285594
user285594

Reputation:

NodeJS - how to manage username and task management without using external databases?

I have the following code, where 1 USER send Ajax query to start a task (washing machine) and after a while it again does Ajax query to check if that task (washing) was completed or not?

How can i track such task (without using/involving any heavy weight MySQL, postgreSQL but just array and objects?)

const https = require('http');
const fs = require('fs');
const url = require('url');

var taskID = 0;
var task = false;

https.createServer((req, res) => {
  try {
    var query =url.parse(req.url,true).query;
    if(query.id=='1') { // Add Task
      res.writeHead(200);

      task = true;
      taskID++;

      console.log('OK - matched: ' + 
                  '1 - execute task now, please come back soon' +
                  '2 - task is not complete yet ' +
      );

      function_do_task_on_end_make_task_flag_false();


    } else if(query.id=='2') { // Check Task status
      res.writeHead(200);
      if(task) {
        res.end("busy");
      } else {
        res.end("done:" + taskID);
      }

    } else {
      res.writeHead(404);     
      console.log('NO - match');
      res.end("req " + query.id);
    }



  } catch(e) {
    console.log(e);
  }
}).listen(8000);

EDIT:

// http://stackoverflow.com/questions/38070287/nodejs-how-to-manage-username-and-task-management-without-using-external-datab?noredirect=1#comment63578743_38070287 
// On server start load data from file
var storage = {tasks: []};
fs.readFile('database.json', function(err, data) {
  if(err) throw new Error(err);
  storage = JSON.parse(data);
});

// On incoming request
if (query.id == '1') {
  // Add task to variable storage
  storage.tasks.push({taskId: query.id, taskName: query.name});
}
else if (query.id == '2') {
  res.json(storage);
}

// Update database persistent file
fs.writeFile('database.json', JSON.stringify(storage), function (err) {
  if (err) throw new Error('Error while serializing DB'); else console.log('DB updated!');
});

Upvotes: 0

Views: 67

Answers (1)

Dmitry Efimenko
Dmitry Efimenko

Reputation: 11203

you can use memory instead of database. Check out node-cache

Upvotes: 1

Related Questions