Using yargs to pass parameters/arguments to a Node script through an npm script

Is it feasible to retrieve a key from yargs when utilizing as an npm script argument?

A user inputs in the OSX terminal:

npm run scaffold --name=blah

which triggers in package.json:

"scaffold" : "node ./scaffold/index.js -- "

This leads to

const yargs = require('yargs').argv

if (yargs) {
  console.log(yargs);
  console.log(yargs.name);
  process.exit(1)
}
...
result:
{ _: [], '$0': 'scaffold/index.js' }
undefined

This method only functions if I embed in package.json

"scaffold" : "node scaffold/index.js --name=blah"
, but I prefer this to be adaptable.

As mentioned, I am using args because it seems to simplify retrieving keys by name (as opposed to an array). Open to suggestions.

What is eluding me?

update 11-07-2017 Related: Sending command line arguments to npm script

However, providing the command line 1: npm run scaffold name=hello OR 2: npm run scaffold --name=hello results in:

1: { _: [], '$0': 'scaffold/index.js' }
2: { _: [ 'name=hello' ], '$0': 'scaffold/index.js' }

Still unable to access the yargs.name property. Remains undefined.


Update 13-07-2017

For now, I have abandoned the effort. It feels impossible. I execute the script manually in the terminal. E.g.

node ./scaffold/index.js --name=blah 

The image below displays running of a node script directly instead of executing via npm scripts. I have included https://www.npmjs.com/package/nopt node module to test if it aids (it does not). process.argv.name remains undefined when run through npm scripts.

https://i.stack.imgur.com/a3QQv.gif


Update 18-07-2017

Added github example: https://github.com/sidouglas/stackoverflow-node-arguments


Update 24-07-2017

Prior declaration of variables before initiating the command proves effective myvar="hello npm run scaffold rather than

npm run scaffold myvar="hello world"

Answer №1

When running scripts as of now, you have the ability to use custom arguments. To separate these custom arguments from regular options, the special option -- is used by getopt. Any arguments following -- will be passed directly to your script by npm:

npm run test -- --grep="pattern"

https://docs.npmjs.com/cli/run-script

Answer №2

Whether the variables are added at the beginning or end of the command line may not be a significant factor. If this detail doesn't concern you, then the following setup will work:

//package.json
{
  "name": "npm-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC"
}    

Here is your JS file:

//index.js
console.log('myvar', process.env.myvar);    

And this is how you would run the command in the terminal:

myvar="hello world" npm run start    

Ultimately, just add your argument list before running your npm script command.

Answer №3

In my experience, the code snippet below has been successful with Node versions 10, 12, and 14:

npm run yourscript -- -- --name=bla

It is important to note that using -- -- is necessary.

Additionally,

"yourscript": "node bla.js"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing. The app is designed to read data from an excel file and import it into a SQL table. During the basic validation process, I noticed that the column headers in ...

The double command in the package.json file is malfunctioning

I am working on an app where I need to bring together all my handlebars templates and partials. When I run the following commands (using npx since it is a local package): Building Views: npx handlebars ./public/templates/views -f ./public/templates/view ...

Create a token for

Visit this link for more information on listing functions in Azure web apps Is there a way to dynamically generate the green-highlighted token using JavaScript or an API? While I'm aware that the token can be generated using Azure CLI by running az a ...

What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files: /* styles/1.scss */ body { /* Some other styles not related to background-color */ } /* styles/2.scss */ body { background-color: blue; } // pages/one.js import "../styles/ ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...

Every time I push my code to Heroku, the deployment runs smoothly. However, I encounter a frustrating 404 error when trying to access

When deploying my app, I encounter an issue where the .glb file in my three.js project receives a 404 resource not found error. Despite trying to adjust the file path without success, the deployment of the entire project is flawless. For local running, I a ...

Updating values of objects during iterations and for get requests is ineffective

Currently, I am looping through multiple select fields and attempting to run a get request for each of them. var selects = { key1 : value } $(".chosen-select-field").each( function ( index ) { selects[key2] = $( this ).attr('data-placeholder& ...

Remove any posts that have a date earlier than the current day

Currently, I am working on a website showcasing events organized by my friend's music label. However, I have run into an issue while attempting to implement an "archiving automation". The code I have tried below is not functioning as expected, as my " ...

Exploring the Interaction between Express.js Requests and Mongoose Models

We're currently in the process of developing a REST API alongside my colleagues using Express.js and Mongoose. As we work with certain Mongoose Model methods and statics, we find the need to have access to the Express.js Request object for additional ...

How to efficiently transfer data between PHP and Javascript using ajax?

Struggling greatly with the ajax function within the jQuery library. As a beginner in jQuery, ajax, and php, I am currently engaged in a school project that involves creating a game-like environment where a 10x10 table generates numbers, selects a cell aut ...

Error: Unable to process reduction on ships - function "reduce" is not functional

I created a boat visualization tool using a specific API. The API responds with a JSON that I then inject into a table. The issue: At times during the day, I observed the application would abruptly stop functioning and throw an error: Unhandled Rejection ...

Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name. However, after clicking on o ...

Learn how to integrate ES6 features into your nodejs/expressjs application using either Gulp or Webpack

I am looking to incorporate ES6 features into my nodejs/expressjs application. Currently, I am using Gulp for JavaScript compilation and setting up live reload. What steps do I need to take in order to compile the es6 code to standard js within my exis ...

An effective way to utilize the h() function in Vuejs to render a component instance

I'm currently working on a Vuejs component setup that resembles the following structure: <template> <button @click="generateItem()">Add item</button> <div class="container"></div> </template> ...

Is there a way to send URL variables to express.js similar to how it's done in PHP?

Currently in the process of converting my PHP website to Express.js. There are numerous scripts on my frontend that generate links in the format page.php?id=10&something=anything. Is there a way in Express.js to capture variables from URLs structured ...

What are the steps to implementing AJAX pagination without utilizing a database?

Is it possible to implement AJAX pagination without relying on MySQL? Can I create a PHP file containing the text and markup needed for display, and by clicking on page numbers, serve that content to the user? Can this be achieved using only jQuery and PHP ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

The utilization of ES Modules within a Next.js server.js

After reviewing a few examples in the Next.js repository, I came across: https://github.com/zeit/next.js/tree/master/examples/custom-server-express https://github.com/zeit/next.js/tree/master/examples/custom-server-koa I observed that these examples ut ...

JavaScript can intelligently extract and categorize an array of objects based on their properties

In essence, I aim to develop a versatile function "organize" that can transform the following data structure: [ { name: 'band1', type: 'concert', subtype: 'rock' }, { name: 'band2', type: 'concert' ...

Display the div only when the radio button has been selected

I have been attempting to tackle this issue for quite some time now, but unfortunately, I haven't had any success. My goal is to display a specific div on the webpage when a particular radio button is selected. While I have managed to achieve this by ...