Is there a way to implement it in scripts
in package.json
somehow without using third-party components?

- 6,742
- 4
- 36
- 54
1 Answers
I'm not sure this is the best solution but I couldn't come up with something better yet. Since I was looking for an approach for Windows console I've checked it only in there, but I think it should work in Linux shell too.
So, we will have 2 JavaScript files:
send-param.js
: should send (return) a string paramread-param.js
: should get that string param as an argument
Both these JS files should be run from scripts of package.json
. The technique itself is pretty simple: the send-param.js
writes a string value to stdout
whereas read-param.js
then gets it as an argument. The main problem was how to "convert" stdout
into an argument for the read-param.js
script.
To write something to stdout
we can use console.log
and that's what send-param.js
actually does:
console.log("Hello World!");
Next, we want to run read-param.js
to get the "Hello World!"
string from arguments but it seems to be impossible to do it directly in Windows console. So I had to use an interim operation to write that argument from stdout
to auxiliary file (I just named it '1.txt'
) and here it's done in the first part of the script:
node send-param.js > 1.txt
Now we have "Hello World!"
in the '1.txt'
file and we have to send it somehow as a parameter the the read-param.js
script. Again, I couldn't find how to do it directly in Windows console and used a variable which I called 'ARG'
:
set /p ARG=<1.txt
Finally, we can use the 'ARG'
variable as an argument for out read-param.js
script:
"node read-param.js %ARG%"
The first thing that came to my mind was to execute all commands in one-line-script like this:
"send-param.js > 1.txt && set /p ARG=<1.txt && node read-param.js %ARG%"
but it wouldn't work since it's required to run set
as a separate command (see why).
In read-param.js
we just read the first argument as process.argv[2]
(Node.js reserves the 0 and 1-st ones for its own arguments).
Here is the final working example:
send-param.js:
console.log("Hello World!");
read-param.js:
const argument = process.argv[2];
if (!argument)
console.log('An argument is required.');
else
console.log(`Argument: '${argument}'`);
package.json:
"scripts": {
"send": "node send-param.js > 1.txt && set /p ARG=<1.txt && npm run read",
"read": "node read-param.js %ARG%",
}
Now run the npm run send
command and you will get: Argument: 'Hello World!'

- 6,742
- 4
- 36
- 54