@gaainf/node-service
TypeScript icon, indicating that this package has built-in type declarations

1.4.0 • Public • Published

build coverage License: MIT

node-service

Run console command as a service using NodeJS. You can start/stop console commands, test STDOUT, STDERR, wait specific conditions, control detached process parameters.

Prerequisites

This project requires NodeJS (version 10 or later) and npm or yarn.

Table of contents

Installation

Before you install: please read the prerequisites

Using npm:

$ npm install @gaainf/node-service

Using yarn:

$ yarn add @gaainf/node-service

Usage

Import

The package contains several classes:

  1. Service is base class to control console command execution, help start it in a detached process.
  2. Services is utility class to repeat console commands started in separate processes, help contol parameters of each of them.

Import Service

const {Service} = require('@gaainf/node-service');

Import Services

const {Services} = require('@gaainf/node-service');

Or import the both:

const {Service, Services} = require('@gaainf/node-service');

Service

Running console command as detached process

const {Service} = require('@gaainf/node-service');

let service = new Service();
service.start('node', ['-v']);
console.log(service.get_pid()); // process ID

Waiting for a command to complete in the background

const {Service} = require('@gaainf/node-service');

async () => {
    let service = new Service();
    service.start('PING', ['1.1.1.1', '-c', '3']);
    console.log(service.get_status());
    // timeout: 3 sec, delay: 1 sec
    await service.wait_condition(() => {return service.get_status() == 'finished'}, 3000, 1000); //boolean function, timeout, delay
    console.log(service.get_status()); // 'finished'
}();

Stopping command

const {Service} = require('@gaainf/node-service');

let service = new Service();
service.start('echo', ['Hello!']);
service.stop();
console.log(service.get_status()); // 'stopped'

Getting stdout and stderr

const {Service} = require('@gaainf/node-service');

(async () => {
    let service = new Service();
    service.start('node', ['-v']);
    await service.wait_condition(() => {return /v/.test(service.get_stdout())}, 1000);
    console.log(service.get_stdout()); // STDOUT
    service.start('node', ['-x']);
    await service.wait_condition(() => {return /bad option/.test(service.get_stderr())}, 1000);
    console.log(service.get_stderr()); // STDERR
})();

Parametrising input properties

Base input properties:

  • cwd - command path
  • args - command arguments
  • timeout - default timeout to test custom output expression (default value is 10 seconds)
  • delay - defualt delay between tries to test custom output expression (default value is 500 milliseconds)
const {Service} = require('@gaainf/node-service');

(async () => {
    let service = new Service({
        cwd: 'node',
        args: ['-e', 'setTimeout(function(){console.log("Hi!")},1000);'],
        timeout: 2000
    });
    service.start();
    await service.wait_condition(() => {return service.get_status() == 'finished'});
    console.log(service.get_stdout());
})();

Calculating duration

const {Service} = require('@gaainf/node-service');

(async () => {
    let service = new Service({cwd: 'node', args: ['-v']});
    service.start();
    await service.wait_condition(() => {return service.get_status() == 'finished'});
    console.log('Duration: ' + service.get_duration() / 1000 + ' sec');
})();

Services

Run several commands and wait until all conditions met

It is possible to run several comands in parallel and wait until all conditions met

const {Service, Services} = require('@gaainf/node-service');

(async () => {
    let services = new Services([
        {cwd: 'node', args: ['-v'], timeout: 1000},
        {cwd: 'node', args: ['--help'], timeout: 1000},
    ]);
    services.start_all();
    await services.wait_all_conditions([
        () => {return services.services[0].get_status() == 'finished'},
        () => {return services.services[1].get_status() == 'finished'}
    ]);
    for(let service of services.services) {
        console.log(service.get_stdout());
    }
    console.log("Duration time: " + services.get_duration());
})();

Repeat specific command until condition met

Following example runs HTTP server in separate process and repeats curl command until the server doesn't respond properly or timeout exceedded. At the end, it prints output data and calculates average duration.

const {Service, Services} = require('@gaainf/node-service');

(async () => {
    // simple HTTP server prints Hi on each request
    let service = new Service({
        cwd: 'node',
        args: [
            '-e', `
            const http = require("http");
            const listener = (req, res) => {res.end('Hi!')};
            http.createServer(listener).listen(8888, '127.0.0.1', () => {});`
        ]
    });

    // Check output via curl
    let curl = new Services({cwd: 'curl', args: ['-m1', 'http://127.0.0.1:8888/'], delay: 1000});
    try {
        // run HTTP server
        service.start();
        // repeat curl command every second
        await curl.repeat(() => {return /Hi!/.test(curl.get_stdout())});
    } finally {
        // be sure to stop the server 
        service.stop();
    }
    // print the last try stdout
    console.log(curl.get_stdout());
    //print average duration
    console.log("Duration time: " + curl.get_duration());
})();

Versioning

SemVer is used. For versions available, please, see tags on this repository.

Authors

  • Alex Grechin - Initial work - gaainf

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.4.0
    1
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.4.0
    1
  • 1.3.0
    0
  • 1.2.0
    0
  • 1.0.0
    0

Package Sidebar

Install

npm i @gaainf/node-service

Weekly Downloads

1

Version

1.4.0

License

MIT

Unpacked Size

41.3 kB

Total Files

14

Last publish

Collaborators

  • gaainf