0

I am trying to follow the instructions here to create a script that prints something every 5 minutes. But it's not working: when I call upon it using node scripts.js alive it gives no output what so ever and just opens a new line in the terminal. What am I doing wrong?

const program = require('commander');

program.command('alive').action(async function() {

    console.log("testttt");

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    };

    for (let i = 0; i <= 36; i++) {
        await sleep(300000);
        console.log(i);
    };

    process.exit(0);
});

I have also tried, with the same result:

    for (let i = 0; i <= 36; i++) {
        await sleep(300000).then(async function(response) {
            console.log(i);
        });
    };
Marty
  • 2,132
  • 4
  • 21
  • 47

3 Answers3

1

The documentation for commander suggests that in order to execute a command you need a line at the end like:

program.parse(process.argv);
backtick
  • 2,685
  • 10
  • 18
1

This script actualy let you do something every seconds.

Run it with node script.js

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

async function func() {
    console.log('func')
    await sleep(1000)
    func()
}

func()

UPDATE - working as requested with commander

Run it with ./script.js -t

#!/usr/bin/env node

const program = require('commander')

program.option('-t, --tick', 'start the ticker')
program.parse(process.argv)

if (program.tick) {
    console.log('program.ticker started')
    ticker()
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

async function ticker() {
    for (let i = 0; i <= 5; i++) {
        await sleep(1000)
        console.log(`tick ${i}`)
    }
    process.exit()
}
Andrea Franchini
  • 548
  • 4
  • 14
  • Are you suggesting to place that within `program.command('alive').action(async function() { }` ? – Marty Jul 09 '19 at 14:06
  • I'm surely not a commander pro. From what i see is possibile that the `.action()` function can't manage async operations, it depends on how it's implemented. What do you need to run in the terminal different from `node script.js` ? – Andrea Franchini Jul 09 '19 at 14:18
  • Thanks, I've created a file with exact that code, and then run `node testfile.js`. However, this produces the same output as in the OP. That is, there is no output and it just goes to a new line in the terminal. – Marty Jul 09 '19 at 17:47
  • Not sure why the updated version doens't work. But the first version does, so I've accepted it as an answer. – Marty Jul 09 '19 at 19:39
0

Hey the problem here is how are you using commander. As you can see here I removed it and it works. Check the documentation of commander.

corrado4eyes
  • 283
  • 2
  • 11