How to pass argument(input) in an npx command to run the npm package

I have an npm package that takes JSON file as input(argument).
I want to know How to pass input via CLI while running an npm package using npx?
I set up the command to run the package but I don’t know how to give input via CLI.
In my package.json file, I have these two commands.

  "bin": {
    "biz-card": "index.js",
    "test": "app.js"

I want to pass an argument to the test command so that it can run the app.js file
app.js file code

 #!/usr/bin/env node

module.export = {
    sayHello: (name) => {
        console.log(`Hello ${name}`);

Anyone can help me with this

process.argv is an array of the arguments passed to the current process, that’s what you use:

1 Like

Hello there,
Thanks for your help.

Now, I did like this.

#!/usr/bin/env node
module.export = {
    sayHello: () => {
        console.log(`Hello ${process.argv[2]}`);

and run this command on terminal
npx -p openapi-test-package-rishi test rishi

But this doesn’t call the sayHello function, it just installed the package, I didn’t see any output.

What am I missing?

Can you please tell me?

#!/usr/bin/env node

console.log(`Hello ${process.argv[2]}`);

It’s a script, it just runs the code then exits. If you just define a function without calling it then it won’t do anything, all you’ve done is written the definition of a function

1 Like

Ok Now I got it

function sayHello() {
  console.log(`Hello ${process.argv[2]}`);

1 Like

One more thing I want to know that If I want to take a file from the command line and then I want to read the data of the file.

How should I do that?

I know I can use fs to read the file? but How I access the path of the file?

Should I take the path of the file as input??

Please give some suggestions

Yes, normally you would take the path of the file as input if you want to allow a user to input any file

so, I think the path should be absolute
or is their any other approach?

Not sure what you mean, you would need to show me an example of what you’re trying to do

Let say user want to convert the file from a HTML to pdf then I need to take the file as a input from the cli and inside our npm package we convert the file.

Should I take the file using file path(absolute or relative path)?

If this doesn’t make sense, please leave this for now.
I’ll give more details about this later on.

Well, wherever you run the script, that folder is the root, so like

const fname = process.argv[2] //or whatever this is
const fpath = path.join(__dirname, fname);

Then run like node ./myscript.js file.html in the folder with the file in

1 Like

Now, I understood.

Thanks for your help

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.