নোড.জেএস দিয়ে একটি কমান্ড লাইন বাইনারি কার্যকর করুন


646

আমি রুবি থেকে নোড.জেএস-তে একটি সি এল এল লাইব্রেরি পোর্ট করার প্রক্রিয়াধীন আমার কোডে আমি প্রয়োজনে বেশ কয়েকটি তৃতীয় পক্ষের বাইনারিগুলি কার্যকর করি। নোডে এটি কীভাবে সেরা তা আমি নিশ্চিত নই।

এখানে রুবির একটি উদাহরণ যেখানে আমি একটি ফাইলকে পিডিএফে রূপান্তর করতে প্রিন্সএক্সএমএল কল করি:

cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")

নোডে সমমানের কোডটি কী?


3
এই গ্রন্থাগারটি শুরু করার জন্য একটি ভাল জায়গা। এটি আপনাকে সমস্ত ওএস প্ল্যাটফর্ম জুড়ে প্রক্রিয়াগুলিকে স্প্যান করার অনুমতি দেয়।
ওবিসিডিয়ান


2
সিম্পলটি হ'ল চাইল্ড_প্রসেস.এক্সেক ব্যবহার করা, এখানে কয়েকটি ভাল উদাহরণ রয়েছে
20:39

উত্তর:


1068

নোড.জেএস (v8.1.4) এর এমনকি আরও নতুন সংস্করণের জন্য, ইভেন্টগুলি এবং কলগুলি পুরানো সংস্করণগুলির মতো বা অনুরূপ, তবে এটি স্ট্যান্ডার্ড নতুন ভাষার বৈশিষ্ট্যগুলি ব্যবহার করতে উত্সাহিত করা হয়েছে। উদাহরণ:

বাফারড, অ-স্ট্রিম বিন্যাসিত আউটপুট (আপনি এটি একবারে পেয়ে যাবেন) এর জন্য ব্যবহার করুন child_process.exec:

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

আপনি এটি প্রতিশ্রুতি সহ ব্যবহার করতে পারেন:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function ls() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
ls();

আপনি যদি ধীরে ধীরে খণ্ডগুলি (স্ট্রিম হিসাবে আউটপুট) ডেটা পেতে চান তবে ব্যবহার করুন child_process.spawn:

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
  // data from standard output is here as buffers
});

// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

এই উভয় ফাংশন একটি সিঙ্ক্রোনাস প্রতিরূপ আছে। উদাহরণস্বরূপ child_process.execSync:

const { execSync } = require('child_process');
// stderr is sent to stderr of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');

পাশাপাশি child_process.spawnSync:

const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);

console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);

দ্রষ্টব্য: নীচের কোডটি এখনও কার্যকরী, তবে প্রাথমিকভাবে ES5 এবং এর আগে ব্যবহারকারীদের লক্ষ্যবস্তু।

Node.js সঙ্গে চাইল্ড প্রসেস ডিম ছাড়ার জন্য মডিউল ভাল নথিভুক্ত করা ডকুমেন্টেশন (v5.0.0)। একটি আদেশ কার্যকর করতে এবং বাফার হিসাবে এর সম্পূর্ণ আউটপুট আনতে, ব্যবহার করুন child_process.exec:

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

আপনার যদি স্ট্রিম সহ হ্যান্ডেল প্রক্রিয়া I / O ব্যবহার করার প্রয়োজন হয় যেমন আপনি যখন প্রচুর পরিমাণে আউটপুট আশা করছেন, তখন ব্যবহার করুন child_process.spawn:

var spawn = require('child_process').spawn;
var child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

// or if you want to send output elsewhere
child.stdout.pipe(dest);

আপনি যদি কোনও কমান্ডের পরিবর্তে কোনও ফাইল চালাচ্ছেন তবে আপনি child_process.execFileযে প্যারামিটারগুলির সাথে প্রায় একইরকম ব্যবহার করতে পারেন spawn, তবে চতুর্থ কলব্যাক প্যারামিটার রয়েছে execআউটপুট বাফার পুনরুদ্ধারের মতো । এটি দেখতে কিছুটা এ জাতীয় দেখাচ্ছে:

var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
  // command output is in stdout
});

V0.11.12 হিসাবে , নোড এখন সিঙ্ক্রোনাস spawnএবং সমর্থন করে exec। উপরে বর্ণিত সমস্ত পদ্ধতি হ'ল অবিচ্ছিন্ন, এবং একটি সংক্রামক সমমনা অংশ রয়েছে। তাদের জন্য ডকুমেন্টেশন এখানে পাওয়া যাবে । এগুলি স্ক্রিপ্টিংয়ের জন্য দরকারী হলেও নোট করুন যে শিশুদের প্রক্রিয়াগুলি অবিচ্ছিন্নভাবে উত্সাহিত করার জন্য ব্যবহৃত পদ্ধতিগুলির বিপরীতে সিঙ্ক্রোনাস পদ্ধতিগুলি উদাহরণ দেয় না ChildProcess


19
ধন্যবাদ. এটি আমাকে বাদাম চালাচ্ছিল। কখনও কখনও এটি কেবল সুস্পষ্ট সমাধানটিকে নির্দেশিত করতে সহায়তা করে যাতে আমরা noobs (নোড করতে) এটি শিখতে এবং এটির সাথে চালাতে পারি।
ডেভ থম্পসন

10
দ্রষ্টব্য: প্রয়োজনীয় ('চাইল্ড_প্রসেস') exec
লুই আমেলিন

2
পরিবর্তে child.pipe(dest)(যা বিদ্যমান নেই), আপনাকে ব্যবহার করতে হবে child.stdout.pipe(dest)এবং child.stderr.pipe(dest), যেমন child.stdout.pipe(process.stdout)এবং child.stderr.pipe(process.stderr)
কমফ্রিচ

যদি আমি সবকিছু একটি ফাইলের মধ্যে রাখতে না চাই, তবে আমি একাধিক কমান্ড কার্যকর করতে চাই? হতে পারে echo "hello"এবং echo "world"
ক্যামেরন

এটি কি এটি করার আদর্শ উপায়? মানে কীভাবে সমস্ত মোড়ক নোডজে লেখা হয়? আমি এর অর্থ জিয়ারম্যান, র‌্যাবিটমিকিউ ইত্যাদির জন্য বলি যার জন্য কমান্ডটি চালানো দরকার তবে তাদের কিছু র‌্যাপারও রয়েছে তবে আমি তাদের লাইব্রেরি কোডে এই
কোডটির

261

নোড জেএস v13.9.0, এলটিএস v12.16.1এবং v10.19.0 --- 2020 মার্চ

অ্যাসিঙ্ক পদ্ধতি (ইউনিক্স):

'use strict';

const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );

ls.stdout.on( 'data', data => {
    console.log( `stdout: ${data}` );
} );

ls.stderr.on( 'data', data => {
    console.log( `stderr: ${data}` );
} );

ls.on( 'close', code => {
    console.log( `child process exited with code ${code}` );
} );


অ্যাসিঙ্ক পদ্ধতি (উইন্ডোজ):

'use strict';

const { spawn } = require( 'child_process' );
const dir = spawn('cmd', ['/c', 'dir'])

dir.stdout.on( 'data', data => console.log( `stdout: ${data}` ) );
dir.stderr.on( 'data', data => console.log( `stderr: ${data}` ) );
dir.on( 'close', code => console.log( `child process exited with code ${code}` ) );


সুসংগত:

'use strict';

const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );

console.log( `stderr: ${ls.stderr.toString()}` );
console.log( `stdout: ${ls.stdout.toString()}` );

নোড.জেএস থেকে v13.9.0 ডকুমেন্টেশন

একই Node.js v12.16.1 ডকুমেন্টেশন এবং Node.js v10.19.0 ডকুমেন্টেশন


8
যথাযথ এবং সাধারণ উভয় সংস্করণ দেওয়ার জন্য আপনাকে ধন্যবাদ। সামান্য সরল সিঙ্ক সংস্করণটি আমার একেবারে বন্ধ করার জন্য পুরোপুরি ঠিক ছিল "আমার কাছে প্রয়োজনীয় স্ক্রিপ্ট" কিছু করুন এবং এটিকে ফেলে দিন।
ব্রায়ান জর্দেন

সমস্যা নেই! কারও কারও মতে এটি "যথাযথ" না হলেও দুজনকেই সর্বদা সুন্দর।
iSkore

7
উইন্ডোতে এই উদাহরণটি করতে গেলে আপনাকে অবশ্যই ব্যবহার করতে হবে 'cmd', ['/c', 'dir']। কমপক্ষে আমি কেবল উচ্চ এবং নিম্ন সন্ধান করছিলাম কেন 'dir'আমি এটি মনে রাখার আগে তর্ক ছাড়াই কাজ করে না ...;)
অ্যান্ডিও

1
এই আউটপুটগুলির কোনওটিই কনসোলে নেই।
Tyguy7

@ টিগুই 7 আপনি কীভাবে এটি চালাচ্ছেন? এবং কনসোল অবজেক্টটিতে আপনার কোনও ওভাররাইড রয়েছে?
iSkore

73

আপনি বাচ্চা_প্রসেস.এক্সেক খুঁজছেন

এখানে উদাহরণ:

const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
    (error, stdout, stderr) => {
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
});

এটা সঠিক। তবে সচেতন থাকুন যে শিশু-প্রক্রিয়াজাতকরণের এই ধরণের স্টাডাউটের দৈর্ঘ্যের সীমাবদ্ধতা রয়েছে।
hgoebl

@ hgoebl, তাহলে বিকল্প কি?
হর্ষদীপ

2
@ হার্শদীপ দীর্ঘ স্টাডআউট আউটপুটগুলির ক্ষেত্রে (বেশ কয়েকটি এমবি যেমন) আপনি স্টাডাউটের dataইভেন্টগুলি শুনতে পারেন । দস্তাবেজগুলিতে দেখুন তবে এটি অবশ্যই এর মতো হবে childProc.stdout.on("data", fn)
hgoebl

30
const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
 //do whatever here
})

14
এই কোডটি কীভাবে কাজ করে এবং কীভাবে এটি উত্তরটি সমাধান করে তার জন্য দয়া করে আরও ব্যাখ্যা যুক্ত করুন। মনে রাখবেন যে স্ট্যাকওভারফ্লো ভবিষ্যতে এটি পড়ার জন্য উত্তরের একটি সংরক্ষণাগার তৈরি করছে।
আল সুইগার্ট

4
আল যা বলেছিলেন তা সত্য, তবে আমি এই উত্তরের সুবিধাটি বলব যে দ্রুত প্রতিক্রিয়া প্রয়োজন এমন ব্যক্তির পক্ষে শীর্ষ উত্তরের মাধ্যমে পড়াটি এত সহজ is

29

সংস্করণ 4 যেহেতু নিকটতম বিকল্পটি হ'ল child_process.execSyncপদ্ধতি:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

নোট করুন যে execSyncকল ব্লক ইভেন্ট লুপ।


এটি সর্বশেষ নোডে দুর্দান্ত কাজ করে। child_processব্যবহার করার সময় কি তৈরি হচ্ছে execSync? এবং ঠিক কমান্ডের পরে এটি সরানো হবে, তাই না? কোন স্মৃতি ফাঁস?
নিকক নিউম্যান

1
হ্যাঁ, কোনও স্মৃতি ফাঁস নেই। আমি অনুমান করি যে এটি কোনও নোডে তৈরি না করে কেবলমাত্র লাইবভ শিশু প্রক্রিয়া কাঠামো সূচনা করে।
পল রুমকিন

21

আপনি যদি এমন কোনও কিছু চান যা শীর্ষের উত্তরটির সাথে সাদৃশ্যপূর্ণ তবে একইসাথে একই রকম হয় তবে এটি কার্যকর হবে।

var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";

var options = {
  encoding: 'utf8'
};

console.log(execSync(cmd, options));

14

আমি সহজেই ইউনিক্স / উইন্ডোজগুলি সহজেই মোকাবেলা করার জন্য একটি ক্লায়াল সহায়ক লিখেছি।

javascript:

define(["require", "exports"], function (require, exports) {
    /**
     * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
     * Requires underscore or lodash as global through "_".
     */
    var Cli = (function () {
        function Cli() {}
            /**
             * Execute a CLI command.
             * Manage Windows and Unix environment and try to execute the command on both env if fails.
             * Order: Windows -> Unix.
             *
             * @param command                   Command to execute. ('grunt')
             * @param args                      Args of the command. ('watch')
             * @param callback                  Success.
             * @param callbackErrorWindows      Failure on Windows env.
             * @param callbackErrorUnix         Failure on Unix env.
             */
        Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
            if (typeof args === "undefined") {
                args = [];
            }
            Cli.windows(command, args, callback, function () {
                callbackErrorWindows();

                try {
                    Cli.unix(command, args, callback, callbackErrorUnix);
                } catch (e) {
                    console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
                }
            });
        };

        /**
         * Execute a command on Windows environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.windows = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(process.env.comspec, _.union(['/c', command], args));
                callback(command, args, 'Windows');
            } catch (e) {
                callbackError(command, args, 'Windows');
            }
        };

        /**
         * Execute a command on Unix environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.unix = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(command, args);
                callback(command, args, 'Unix');
            } catch (e) {
                callbackError(command, args, 'Unix');
            }
        };

        /**
         * Execute a command no matters what's the environment.
         *
         * @param command   Command to execute. ('grunt')
         * @param args      Args of the command. ('watch')
         * @private
         */
        Cli._execute = function (command, args) {
            var spawn = require('child_process').spawn;
            var childProcess = spawn(command, args);

            childProcess.stdout.on("data", function (data) {
                console.log(data.toString());
            });

            childProcess.stderr.on("data", function (data) {
                console.error(data.toString());
            });
        };
        return Cli;
    })();
    exports.Cli = Cli;
});

মূল উত্স ফাইল টাইপস্ক্রিপ্ট:

 /**
 * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
 * Requires underscore or lodash as global through "_".
 */
export class Cli {

    /**
     * Execute a CLI command.
     * Manage Windows and Unix environment and try to execute the command on both env if fails.
     * Order: Windows -> Unix.
     *
     * @param command                   Command to execute. ('grunt')
     * @param args                      Args of the command. ('watch')
     * @param callback                  Success.
     * @param callbackErrorWindows      Failure on Windows env.
     * @param callbackErrorUnix         Failure on Unix env.
     */
    public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
        Cli.windows(command, args, callback, function () {
            callbackErrorWindows();

            try {
                Cli.unix(command, args, callback, callbackErrorUnix);
            } catch (e) {
                console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
            }
        });
    }

    /**
     * Execute a command on Windows environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(process.env.comspec, _.union(['/c', command], args));
            callback(command, args, 'Windows');
        } catch (e) {
            callbackError(command, args, 'Windows');
        }
    }

    /**
     * Execute a command on Unix environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(command, args);
            callback(command, args, 'Unix');
        } catch (e) {
            callbackError(command, args, 'Unix');
        }
    }

    /**
     * Execute a command no matters what's the environment.
     *
     * @param command   Command to execute. ('grunt')
     * @param args      Args of the command. ('watch')
     * @private
     */
    private static _execute(command, args) {
        var spawn = require('child_process').spawn;
        var childProcess = spawn(command, args);

        childProcess.stdout.on("data", function (data) {
            console.log(data.toString());
        });

        childProcess.stderr.on("data", function (data) {
            console.error(data.toString());
        });
    }
}

Example of use:

    Cli.execute(Grunt._command, args, function (command, args, env) {
        console.log('Grunt has been automatically executed. (' + env + ')');

    }, function (command, args, env) {
        console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');

    }, function (command, args, env) {
        console.error('------------- Unix "' + command + '" command failed too. ---------------');
    });


7

এখন আপনি নীচে শেলজগুলি (নোড ভি 4 থেকে) ব্যবহার করতে পারেন:

var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version')

6

যদি আপনি কোনও নির্ভরতা মনে করেন না এবং প্রতিশ্রুতি ব্যবহার করতে চান, child-process-promiseকাজ করুন:

স্থাপন

npm install child-process-promise --save

এক্সিকিউটিভ ব্যবহার

var exec = require('child-process-promise').exec;

exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

স্প্যান ব্যবহার

var spawn = require('child-process-promise').spawn;

var promise = spawn('echo', ['hello']);

var childProcess = promise.childProcess;

console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});

promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

4

এই লাইটওয়েট npmপ্যাকেজটি ব্যবহার করুন :system-commands

এখানে এটি দেখুন ।

এটি এর মতো আমদানি করুন:

const system = require('system-commands')

কমান্ডগুলি এর মতো চালান:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})

পারফেক্ট! আমার প্রয়োজনের জন্য দুর্দান্ত কাজ করে।
রোজভেল্ট

3

@ হেক্সাসায়ানাইডের উত্তরটি প্রায় সম্পূর্ণ। উইন্ডোজ কমান্ড princeহতে পারে prince.exe, prince.cmd, prince.batবা শুধু prince(আমি কিভাবে রত্ন বান্ডেল করা কোন সচেতন, কিন্তু npm বিন একটি SH স্ক্রিপ্ট এবং একটি ব্যাচ স্ক্রিপ্ট সঙ্গে আসা - npmএবং npm.cmd)। আপনি যদি কোনও পোর্টেবল স্ক্রিপ্ট লিখতে চান যা ইউনিক্স এবং উইন্ডোতে চলতে পারে তবে আপনাকে সঠিক এক্সিকিউটেবল স্প্যান করতে হবে।

এখানে একটি সহজ তবে বহনযোগ্য স্পন ফাংশন:

function spawn(cmd, args, opt) {
    var isWindows = /win/.test(process.platform);

    if ( isWindows ) {
        if ( !args ) args = [];
        args.unshift(cmd);
        args.unshift('/c');
        cmd = process.env.comspec;
    }

    return child_process.spawn(cmd, args, opt);
}

var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])

// Use these props to get execution results:
// cmd.stdin;
// cmd.stdout;
// cmd.stderr;
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.