NPM custom arguments produces Powershell error - powershell

I am trying to launch a npm script with a custom argument:
"publish-local": "ng build $PROJECT && cd dist/$PROJECT && npm publish --registry=http://my.local.npm.registry"
This is how I am trying to call it from the prompt:
PROJECT=my-lib npm run publish-local
This is how I have seen it should work on different web sources (for example:here)
Anyway, trying to do that, I get this error:
PROJECT=my-lib: The term 'PROJECT=my-lib' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
What to do?

Short answer: The example(s) that you've seen that "should work" will only work on *nix. They do not work via PowerShell, nor via Command Prompt on Windows.
Given that you're wanting to pass an argument to a npm-script, whereby that argument is consumed two times in the middle of that script I suggest you consider the following approach instead:
The following suggested approach is very similar to my answer here.
Solution - Cross-platform:
For a cross-platform solution, (one which works successfully with *nix, Windows Command Prompt and PowerShell etc..), you'll need to utilize a nodejs helper script.
Let's name the nodejs script publish-local.js and save it in the projects root directory, at the same level as package.json.
publish-local.js
const execSync = require('child_process').execSync;
const arg = process.argv[2] || 'my-lib'; // Default value `my-lib` if no args provided via CLI.
execSync('ng build ' + arg + ' && cd dist/' + arg +
' && npm publish --registry=http://my.local.npm.registry', {stdio:[0, 1, 2]});
package.json
Configure your publish-local script to invoke publish-local.js as follows:
...
"scripts": {
"publish-local": "node publish-local",
},
...
Running publish-local script:
To invoke publish-local via your CLI you'll need to run:
npm run publish-local -- my-lib
Notes:
Inside publish-local.js take note of the line that reads:
const arg = process.argv[2] || 'my-lib'; // Default value `my-lib` if no args provided via CLI.
It specifies a default value to use when no argument is provide via the CLI.
So, If you were to currently run the npm script without passing an argument:
npm run publish-local
or run it with passing an argument:
npm run publish-local -- my-lib
They are essentially the same. However if you were to provide an argument that is different to my-lib, i.e. one that is different to the default specified in publish-local.js, it will take precedence. For example:
npm run publish-local -- some-other-lib
For a further understanding of this solution I suggest you read my answer that I previously linked to.
The default shell used by npm is cmd.exe on Windows, and sh on *nix - this given solution will work successfully with either.
If you only intend to use/support more recent versions of node.js that support ecmascript-6 features, such as destructuring, template literals then you could refactor publish-local.js as follows:
publish-local.js (refactored using ES6 features)
const { execSync: shell } = require('child_process');
const [ , , projectName='my-lib' ] = process.argv;
shell(`ng build ${projectName} && cd dist/${projectName} && npm publish --registry=http://my.local.npm.registry`, {stdio:[0, 1, 2]});

Related

Configure ZSH to always fall back to path completion

I'm using zsh, and the completions mostly just work. But when I use various commands where an arbitrary command follows a command with specialized zsh handling, file path completions don't work.
# completes to 'npm run build' for a package.json with a 'build' script
npm run b<tab>
# does not complete the file path (to, say, `datafile/somefile.json`)
npm run build -- datafile/som<tab>
Obviously, npm has a configured completion definition that loads the package.json and understands valid args. But after -- the remaining args are just passed through, and I'd like file completion to be the default.
Is there a way to have zsh always fallback to path completion OR maybe have the -- indicator commonly used to indicate end or arguments to turn back on default completions.

Pass values from cmd to npm script

I've searched for days but did not find an answer that worked for my problem.
I want to run a npm script through cmd or Powershell in Windows and pass values for script variables.
I would like the bellow script in package.json:
"scripts": {
"happy-birthday": "echo Happy birthday $NAME and many returns!"
}
To output:
Happy birthday Danny and many returns!
With a command like:
npm run happy-birthday --NAME=Danny
Everything I tested so far gives me:
Happy birthday $NAME and many returns!
It feels like npm does not recognize this as a variable and prints it like it is a string. I also tested %NAME%.
Npm version - 6.12.1
You can't pass arguments to the middle of npm scripts, argument(s) can only be passed to the end of them. See my answer here for further explanation.
Given your example, consider the following solution which will work successfully across all platforms:
In your package.json file define your happy-birthday npm script as follows:
"scripts": {
"happy-birthday": "node -e \"console.log('Happy birthday %s and many returns!', process.argv[1] || 'Jane')\""
}
Then run the following command via cmd or Powershell (or any other command line tool).
npm run happy-birthday -- Danny
This will print:
Happy birthday Danny and many returns!
Note: If you just run the following command, i.e. without passing an argument:
npm run happy-birthday
It will print the default name instead:
Happy birthday Jane and many returns!
Explanation:
The npm script utilizes the nodejs command line option -e to evaluate the inline JavaScript as follows:
console.log('Happy birthday %s and many returns!', process.argv[1] || 'Jane')
The arguments passed via the CLI, e.g. Danny, are read using process.argv - whereby we reference the Array element at index 1.
The Logical OR Operator, i,e. || is utilized to return Jane when no argument is passed.
Edit: Setting environment variables instead
Alternatively may want to consider setting an environment variable and referencing it in your npm script.
In your npm script define your happy-birthday npm script as follows:
"happy-birthday": "echo Happy birthday %NAME% and many returns!"
Note the %NAME% notation used by Windows only to reference the variable.
Using cmd
When using cmd (i.e. Command Prompt) you'll need to run the following command:
set NAME=Danny&& npm run happy-birthday
Using Powershell
When using Powershell you'll need to run the following command instead:
$env:NAME="Danny" ; npm run happy-birthday
Note: The default shell that npm utilizes for npm scripts is sh on *nix and cmd on windows. Therefore the aforementioned methods defined in steps 1 and 2 will fail on *nix platforms.
If cross-platform support is requirement and you do want to take this approach of setting environment variables and referencing them via npm scripts, then consider utilizing the cross-env package.

Recommended way to run commands after installing dependencies in the virtualenv

I would like to use tox to run py.test on a project which needs additional setup in addition to installing packages into the virtualenv. After creating the virtualenv and installing dependencies, some commands need to be run.
Specifically I'm talking about setting up a node and npm environment using nodeenv:
nodeenv --prebuilt -p
I see that tox allows me to provide a custom command used for installing dependencies by setting install_command in tox.ini. But I don't think this is what I want because that replaces the command (I assume pip) used to install dependencies.
I thought about using a py.test fixture with session scope to handle setting up nodeenv but that seems hacky to me as I don't want this to happen when py.test is run directly, not via tox.
What is the least insane way of achieving this?
You can do all necessary setup after the creation of the virtualenv and the dependency installation in commands. Yes, it says "the commands to be called for testing." but if you need to do extra work to prepare for testing you can just do it right there.
It works through whatever you throw at it in the order it is given - e.g.:
[testenv:someenv]
deps =
nodeenv
pytest
flexmock
commands =
nodeenv --prebuilt -p
; ... and whatever else you might need to do
py.test path/to/my/tests
If you have commands/scripts or whatever else that produces the right result but it returns a non zero exit status you can ignore that by prepending - (as in - naughty-command).
If you need more steps to happen you can wrap them in a little (Python) script and call that script instead as outlined in https://stackoverflow.com/a/47834447/2626627.
There is also an issue to add the ability to use more than one install command: https://github.com/tox-dev/tox/issues/715 is implemented.
I had the same issue, and as it was important for me to be able to create the environment without invoking the tests (via --notest), I wanted the install to happen in the install phase and not the run phase, so I did something slightly differently. First, I created a create-env script:
#!/usr/bin/env sh
set -e
pip install $#
nodeenv --prebuilt --python-virtualenv --node=8.2.1
Made it executable, Then in tox.ini:
[tox]
skipsdist = True
[testenv]
install_command = ./create-env {opts} {packages}
deps = nodeenv
commands = node --version
This complete example runs and outputs the following:
$ tox
python create: .../.tox/python
python installdeps: nodeenv
python installed: nodeenv==1.3.0
python runtests: PYTHONHASHSEED='1150209523'
python runtests: commands[0] | node --version
v8.2.1
_____________________________________________________________________ summary ______________________________________________________________________
python: commands succeeded
congratulations :)
This approach has the downside that it would only work on Unix.
In tox 715, I propose the possibility of native support for multiple install commands.

Ember.js fails to install globally

I ran the command to install Ember.js:
npm install -g ember-cli
Then when I run:
Ember -v
I get error: "The term ember is not recognized as the name of a cmdlet, function, script file or operable program ..."
I added the system environment variable $NODE_PATH = %AppData%\npm\node_modules
I see ember-cli folder in the $NODE_PATH
This is a newly imaged machine so this may be an issue with my npm setup/configuration. How can I install ember globally?
I added %AppData%\npm (use the full path which in my case is C:\Users\bmackey\AppData\Roaming\npm) to the system Path environment variable. I had to remove C:\Program Files\Microsoft DNX\Dnvm\ from my Path in order to stay under the 260 character limit; hopefully I won't need this. I do not know a way around the 260 character limit.
Now ember -v works.
You need to add the path to the ember.cmd file into the powershell environment variable, note that this is different to the standard PATH environment variable.
For those that don't know, the reason you can run ember (a node module) simply by running the command ember is because when you install ember it create a ember.cmd file in your AppData folder:
this file typically looks like this and just bootstraps node and runs the ember js file:
#IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\node_modules\ember-cli\bin\ember" %*
) ELSE (
#SETLOCAL
#SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\node_modules\ember-cli\bin\ember" %*
)
so when you run ember from your command window or powershell it just looks for a cmd file in its PATH variable. If this doesn't have an entry pointing at the location of this cmd file it won't be able to run it.
To fix this in powershell just run the following:
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Users\<user>\AppData\npm", [EnvironmentVariableTarget]::Machine)
Most of this is taken from the answer here.
Make sure C:\Users\<user>\AppData\npm is where NPM has deployed your ember.cmd file. I have seen this also deploy in C:\Users\<user>\AppData\Roaming\npm so it can vary.

Executing subprocess.Popen inside Python script in PyDev context is different than running in terminal

I'm executing this code:
p = subprocess.Popen(['/path/to/my/script.sh','--flag'] , stdin=subprocess.PIPE)
p.communicate(input='Y')
p.wait()
It works when executing it on the shell using "python scriptName.py",
BUT when executing using PyDev in Eclipse, it fails, the reason:
/path/to/my/script.sh: line 111: service: command not found
This bash script "script.sh" contains the following command which causes the error:
service mysqld restart
So "service" is not recognized when running the .sh script from the context of PyDev.
I guess it has to do with some ENV VAR configurations, couldn't find how to do it.
BTW - Using "shell=True" when calling subprocess.Popen didn't solve it.
service usually is located in /usr/sbin, and that this directory isn't on the PATH. As this usually contains administrative binaries and scripts which arn't designed to be run by everyone (only by admins/root), the sbin directories arn't always added to the PATH by default.
To check this, try to print PATH in your script (or add an env command).
To fix it, you could either
set the PATH in your python script using os.setenv
pass an env dict containing the correct PATH to Popen
set the PATH in your shellscript
use the full path in your shellscript
set the PATH in eclipse