Monday, March 2, 2020

How would you pass an arbitrary number of additional parameters from process.agrv to the spwaned process?

I am following the book "Node.js 8 the right way"

here is a question to expand the functionality from book. How would you pass an arbitrary number of additional parameters from process.agrv to the spwaned process?

here is original code to monitor the file changes with command being hard code.

'use strict';
const fs=require('fs');
const spawn=require('child_process').spawn;
const filename=process.argv[2];

if(!filename){
    throw Error('A file to watch must be specified');
}
fs.watchFile(filename, ()=>{
    const ls=spawn('ls',['-l''-h'filename]);
    let output='';
    ls.stdout.on('data'chunk=>output +=chunk);
    ls.on('close', ()=>{
        const parts=output.split(/\s+/);
        console.log(parts[0], parts[4], parts[8]);
    })
});

console.log('Now watching target.txt for change.....');


 Now we can change the code handle arbitrary number of parameters. here is the spawn method child_process.spawn(command[, args][, options). we need to use an array to build the argument portion.

let options=[];
for (var i = 4i < process.argv.lengthi++) {
    options.push(process.argv[i]);
}
options.push(filename);

We can integrate the above code into our new program, then the program can accept any number of parameters. 

node watcher-spawn-cmd.js target.txt ls -l -h

 node watcher-spawn-cmd.js target.txt ls -l -h -s



'use strict';
const fs=require('fs');
const spawn=require('child_process').spawn;
const filename=process.argv[2];
const commandname=process.argv[3];

let options=[];
for (var i = 4i < process.argv.lengthi++) {
    options.push(process.argv[i]);
}
options.push(filename);

if(!filename){
    throw Error('A file to watch must be specified');
}

fs.watchFile(filename, ()=>{
    const ls=spawn(commandname, options);  
    let output='';
    ls.stdout.on('data'chunk=>output +=chunk);
    ls.on('close', ()=>{
        const parts=output.split(/\s+/);
        console.log(parts[0], parts[4], parts[8]);
    })
});

console.log('Now watching target.txt for change.....');








No comments:

Post a Comment