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

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

Unable to configure node and express for file serving

Currently using Windows 7, I have successfully installed nodes 0.10.12 and the latest versions of express and express-generator globally. I then proceeded to create a new express project called nodetest1 and installed all dependencies using npm install. U ...

Creating line breaks for ToolTip titles in Material-UI can be achieved by using the appropriate syntax and

I am currently working with the ToolTip component and I have a query regarding displaying two lines for the title text - one line for each language rather than having them displayed on a single line. Is it possible to achieve this and how can I style the c ...

Implementing type-based validations in Vue.js 3 using Yup

Greetings! I am facing a minor issue that needs to be addressed. The scenario is as follows: I need to implement validation based on the type of member. If the member type is corporate, then the tax number should be mandatory while the phone number can be ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

Returning to the initial state after clicking on an element within a repeated set in AngularJS?

I'm currently facing a challenge, mainly due to my lack of understanding in basic AngularJs concepts. The issue arises when I interact with a list of clickable words. When I click on any of these words, their color changes individually thanks to the i ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> Is there a way I can mak ...

Why is my AngularJS application triggering two events with a single click?

<button id="voterListSearchButton" class="serachButton" ng-click="onSearchButton1Click()">find</button> This button allows users to search for specific information: $scope.onSearchButton1Click = function() { var partId = $("#partIdSearch" ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

Is there a way to update a JSON key using the "onchange" function in React?

I'm facing an issue. I have a form with two inputs. The first input is for the key and the second input is for the value. I need to update the values in the states whenever there is a change in the input fields, but I'm unsure of how to accomplis ...

Creating a seamless navigation experience using Material UI's react Button and react-router-dom Link

Is there a way to have the Material UI react Button component behave like a Link component from react-router-dom while preserving its original style? Essentially, how can I change the route on click? import Button from '@material-ui/core/Button' ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

Socket.io: sending signals without receiving any responses

I've been working on a real-time socket.io project that involves a collaborative whiteboard app. I'm facing some issues with emitting data. server.js const express = require('express') const app = express(); const http = require(&apos ...

Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID. As an illustration, if the original array (let's ca ...

Can you identify the issue with my database file?

Here is the content from my database.js file: const MongoClient = require('mongodb').MongoClient; const db = function(){ return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => { if (err) return co ...

Updating a singular value in an array using jQuery/JavaScript

Within a Javascript function, I have created an array called HM_Array1. The contents of the array are listed below: HM_Array1 = [[,11,147,,,,,,,1,1,0,0,0,1,"csiSetBorder(this)","null",,,true,["&nbsp;&nbsp;&nbsp;Accoun&nbsp;&nbsp;& ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

Retrieving the chosen option in Vue.js when the @change event occurs

I have a dropdown menu and I want to perform different actions depending on the selected option. I am using a separate vue.html and TypeScript file. Here is my code snippet: <select name="LeaveType" @change="onChange()" class="f ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...