Mythriel
Mythriel

Reputation: 1380

how to make a tracking timer in command line with node.js

I am trying to build a simple time tracking tool in the command line and and basically i want to run start and stop commands and output the time elapsed. At the moment I am having problems because my timer variable is not holding values between requests. This is the simple script I have wrote until now; Do I need to spawn another process or should I just store the start time in a .txt file or database and use it from there?

#! /usr/bin/env node

var cli = require('commander'),
    time,
    timer = null;

cli
    .version('0.0.1');

cli
    .command('start')
    .description('Start timer')
    .action(start);

cli
    .command('stop')
    .description('Stop timer')
    .action(stop);

cli.parse(process.argv);

function start() {
    timer = new Date;
}

function stop() {
    time = new Date - timer;
    hours = Math.floor(time/3600);
    seconds = time % 3600;
    minutes = Math.floor(seconds / 60);
    seconds = seconds % 60;
    seconds = Math.floor(seconds);

    console.log(hours + ' hours ' + minutes + ' minutes ' + seconds + " seconds")
}

Upvotes: 0

Views: 706

Answers (1)

user336242
user336242

Reputation:

Without some external mechanism for storing state of ay kind (such as a database, flat file, etc) each invocation of your program will have no knowledge of what happened in any other invocation of it.

Each time you run the application all the variables are initialized, written to, read from, etc and then once your application stops everything is then binned, any memory it has used is returned to the operating system and all your variables disappear.

The simplest way to persist time would probably to have your code read and write to a flat file (maybe in a json format). This does have potential issues such as concurrency and file locking but I wouldn't worry about this till they actually become a problem. (and then you can just use a database etc).

Upvotes: 1

Related Questions