How to pass flags to nodejs application through npm run-script? - javascript

I've a NodeJS file that I run via an "npm" command. I've been trying to list all arguments (including flags). If I run it by directly calling the node exe, it works fine but if I use the npm command, I cannot access the flags.
Code:
console.dir(process.argv);
When I run the file like this,
node file.js arg1 arg2 -f --flag2
I can get all of the arguments.
[ '/usr/local/bin/node',
'/.../file.js',
'arg1',
'arg2',
'-f',
'--flag2' ]
But if I add an npm runner to the package.json file and try to run with it, I can only get the arguments but not the flags.
npm run test arg1 arg2 -f --flag2
The result:
[ '/usr/local/bin/node',
'/.../file.js',
'arg1',
'arg2' ]
package.json file:
{
"name": "name",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test" : "node test.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Basically, node won't pass flags to the running script. Is there a solution for this? My real project has a long path with a lot of arguments so I want to use a shortcut to test it.

Use a double dash before arguments:
npm run test -- arg1 arg2 -f --flag2

Related

Cannot find module with **/*.test.js

I'm trying to set up testing for my Next.js project. I want to test it with RITEway which is based on tape. I want a test command that finds all files in my src/ folder that end with .test.js.
Here is the commend I came up with:
"test": "NODE_ENV=test node -r #babel/register src/**/*.test.js",
I get the error:
Error: Cannot find module '/path/to/project/src/**/*.test.js'
How can I tell node to find all files ending in .test.js in my src/ folder?
Extra context:
My testing files live in src/features/<feature>/<feature.test.js>, e.g.:
"test": "NODE_ENV=test node -r #babel/register src/features/home/home-page-component.test.js",
Works to find a single file and run it.
"test": "NODE_ENV=test node -r #babel/register src/**/**/*.test.js",
Works to find all folders in features, but ignores files like src/<file>.test.js, which I also want to run.
I had to install #babel/register and #babel/core for Node to process absolute imports and newer syntax.
My .babelrc is:
{
"env": {
"test": {
"plugins": [
[
"module-resolver",
{
"root": [
"."
],
"alias": {
"features": "./src/features"
}
}
]
]
}
},
"presets": [
[
"next/babel"
]
],
"plugins": []
}
As Jon Sharpe said, you have to feed the regex into riteway.
"test": "NODE_ENV=test riteway -r #babel/register 'src/**/*.test.js'",

Cannot find modules that have been installed locally by NPM

I am working on a tool and I have installed some modules locally through NPM, and I get errors when I try to require these modules through NodeJS. I am working in Windows 10, I have already tried setting up NODE_PATH etc.
Below is the structure of my files:
->project
---->node_modules
---->src
-------->css
-------->js
----------->index.js
---->package.json
---->index.html
I populate the index.html by using index.js etc.
Below is the code of my package.json:
{
"name": "bip39",
"version": "1.0.0",
"description": "A tool for converting BIP39 mnemonic phrases to addresses and private keys.",
"directories": {
"test": "tests"
},
"dependencies": {
"bip39": "^2.6.0",
"bigi": "^1.4.2",
"create-hmac": "^1.1.7",
"nem-sdk": "^1.6.7"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/PavlosTze/bip39.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/PavlosTze/bip39/issues"
},
"homepage": "https://github.com/PavlosTze/bip39#readme"
}
Below is my require() code:
var createHmac = require("create-hmac");
var BigInteger = require("bigi");
const bip39 = require("bip39");
const nem = require("nem-sdk").default;
I have done the following steps on NPM:
1) npm init
2) npm install bip39
3) npm install nem-sdk
4) npm install bigi
5) npm install create-hmac
All these files are inside the node_modules, but still, whenever I run the code in the browser I get an 'Error: Cannot find module "bip39"', etc. for all modules.
EDIT: On another directory that I have cloned the same tool, before I merged it with another one, I get no error and everything works correctly, including the require(). etc. Do you need any of those files as well?
Can someone help me please?
try this :
rm -rf node_modules
npm install

$PWD in npm script

Is there a way to concat $PWD with a string in package.json
I am trying:
"config": {
"mypath" : "$(pwd)/assets/dist/js"
}
But it doesn't seem to work. Is it a way to access the current working path?
It works if I use it in a script. e.g.
"scripts": {
"echo" : "echo $(pwd)/assets/dist/js"
}
Don't know your exact use-case, but you could use $npm_package_config_path in your script to pass it as an argument:
"config" : {
"path": "/assets/dist/js"
},
"scripts" : {
"something":"CONFIG_PATH=${PWD}$npm_package_config_path node -e \"console.warn(process.env.CONFIG_PATH)\"",
}
}
Then:
$> npm run something
/path/to/your/dir/assets/dist/js
I don't know where do You want to use config.mypath value but if you want to use this value in a script You could use this approach:
Before to start We have to know that: npm uses several programs to run the scripts. As default it uses bash in gnu/linux and cmd in windows (We can set the shell as in this question ). Therefore every script should be created to run over bash or cmd and often They are not compatibles.
Now let's get to work
You could get config.mypath value as follows:
"config": {
"mypath" : "${PWD}/assets/dist/js"
},
"scripts": {
"show-path": "echo $npm_package_config_mypath"
}
and run the command
npm run show-path
and the output would show us the config.path value
${PWD}/assets/dist/js
of course this is not the value You want... but We can work with these value in a shell to get what We want.
In bash We can use the next syntax to execute commands:
echo [comand] |grep bash
for example:
echo echo \${PWD}/assets/dist/js | bash
is the same as:
echo ${PWD}/assets/dist/js
and the output is:
/home/user/assets/dist/js
And I think these output is the value You want to read and use in your scripts...
Now We can implement this trick to our package.json
a) linux(bash):
"config": {
"mypath" : "${PWD}/git_repo"
},
"scripts": {
"config": "echo echo $npm_package_config_mypath |bash",
"git-clone": "echo git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY ${npm_package_config_mypath}-foo | bash"
}
b) windows(cmd): in windows pwd works in powershell but in CMD pwd does not exist. Then we have to use %cd% and write our scripts with CMD syntax...
"config": {
"mypath": "%cd%\\git-repo"
},
"scripts": {
"config": "echo echo %npm_package_config_mypath% | cmd",
"git-clone": "echo git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY %npm_package_config_mypath%-foo | cmd"
}
In the examples config.mypath is used to create two scripts:
config: prints config.mypath value
git-clone: clones a repository in the config.mypath folder

How do I execute different Testcases with different structure through NodeJS and Mocha

How do I execute different Testcases with different structure through NodeJS and Mocha.
Moving forward I intend to integrate Selenium + NodeJS + Mocha
I have just started to explore NodeJS with Mocha and need some help.
Installed node.js:
C:\Users\AtechM_03>node -v
v6.11.2
Installed npm:
C:\Users\AtechM_03>npm -v
3.10.10
Configured nodeclipse as per this link and my Project structure looks like:
Installed Mocha at the default location (through command-line) as per this link.
C:\Users\AtechM_03>npm install -g mocha
C:\Users\AtechM_03\AppData\Roaming\npm\mocha -> C:\Users\AtechM_03\AppData\Roaming\npnode_modules\mocha\bin\mocha
C:\Users\AtechM_03\AppData\Roaming\npm\_mocha -> C:\Users\AtechM_03\AppData\Roaming\n\node_modules\mocha\bin\_mocha
C:\Users\AtechM_03\AppData\Roaming\npm
`-- mocha#3.5.3
Followed this link to write a program in NodeJS integrating Mocha.
Created a directory named test with in NodeProject space.
Within test folder created a file named test.js
Executed npm init to interactively create a package.json file.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) test
version: (1.0.0) 1.0.0
description: test123
entry point: (index.js) test.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjan
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Is this ok? (yes)
C:\Users\AtechM_03\LearnAutmation\NodeProject>
package.json got generated within the Project Scope i.e. under C:\Users\AtechM_03\LearnAutmation\NodeProject as follows:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Added code to test.js as follows:
// Require the built in 'assertion' library
var assert = require('assert');
// Create a group of tests about Arrays
describe('Array', function() {
// Within our Array group, Create a group of tests for indexOf
describe('#indexOf()', function() {
// A string explanation of what we're testing
it('should return -1 when the value is not present', function(){
// Our actual test: -1 should equal indexOf(...)
assert.equal(-1, [1,2,3].indexOf(4));
});
});
//Create a test suite (group) called Math
describe('Math', function() {
// Test One: A string explanation of what we're testing
it('should test if 3*3 = 9', function(){
// Our actual test: 3*3 SHOULD EQUAL 9
assert.equal(9, 3*3);
});
// Test Two: A string explanation of what we're testing
it('should test if (3-4)*8 = -8', function(){
// Our actual test: (3-4)*8 SHOULD EQUAL -8
assert.equal(-8, (3-4)*8);
});
});
});
Executed npm test from project space which runs successfully:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Followed this link to write a second program in NodeJS integrating Mocha.
Created a separate directory named temperature with in NodeProject space.
In the temperature directory created a file named app.js and a folder name test
Within the test folder, created a file named test.js
Moved the previous package.json to a sub-directory and executed npm init to interactively create a new package.json file again.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) temperature
version: (1.0.0) 1.0.0
description: temp
entry point: (index.js) app.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjanb
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
Is this ok? (yes)
New package.json gets created as follows:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
The current temperature Testcase looks like:
Tried to execute this second program through npm test from the Project space but it still executes the first program as follows:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Question :
I know my second program app.js is incomplete and executing it will show error (e.g. 0 passing (20ms)) but my app.js is not getting invoked at all.
Can someone please guide/suggest me what I am doing wrong here?
Any suggestion/guide/pointer will be helpful.
Update:
As of now my current code for app.js is incomplete and contains the following code:
cToF = function(celsius) {
if(!Number.isInteger(celsius)) return undefined;
return celsius * 9 / 5 + 32;
}
fToC = function(fahrenheit) {
if(!Number.isInteger(fahrenheit)) return undefined;
return (fahrenheit - 32) * 5 / 9;
}
As per this website I am following I expect an error as 0 passing (20ms)
You've got quite the long description but the thing I extracted from it is that you have essentially a structure like this:
NodeProject
├── temperature
│   └── test
└── test
Then you go into NodeProject and run Mocha. By default Mocha will look only for test in the same directory where it is invoked. So it won't look for temperature/test. If you want Mocha to run the tests in temperature/test you have to tell Mocha explicitly. For instance, this would work:
mocha test temperature/test
I'll address a common misconception here because I often see people make the mistake: merely using the --recursive flag is not enough. If you use this flag, then after Mocha has identified directories in which to find tests, it will look in them recursively. However, it does not change how Mocha identifies directories in which to find tests. Specifically, if you use mocha --recursive, it will still only look in test, and it will look in subdirectories of test. This won't make it look in temperature/test. If you do have subdirectories in test and temperature/test, you could do:
mocha --recursive test temperature/test

Command not found after npm link

I have a small node.js app "doto" that I want to npm link, so that I can just call doto anywhere. As of my understanding all I need to do is:
mkdir doto
cd doto
npm init #call the project doto and entry point doto.js
touch doto.js #fill with some code
npm link
node doto.js works just fine, but when I link the package and try to call doto, the command is not found. The linking went fine, I had to use sudo (yes I know I should setup node a way that I do not need sudo, but for now I just want to get my feet wet)
Whenever I install a package globally, I can call it just fine.
I am running mac os 10.10.
doto.js
#!/usr/bin/env node
var path = require('path');
var pkg = require( path.join(__dirname, 'package.json') );
var program = require('commander');
program
.version(pkg.version)
.option('-p, --port <port>', 'Port on which to listen to (defaults to 3000)', parseInt)
.parse(process.argv);
console.log(program.port);
package.json
{
"name": "doto",
"version": "0.0.1",
"description": "",
"main": "doto.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "~2.7.1"
}
}
What am I missing?
I think your package.json is missing the bin section, according to the docs it should become something like:
{
"name": "doto",
"version": "0.0.1",
"description": "",
"main": "doto.js",
// specify a bin attribute so you could call your module
"bin": {
"doto": "./doto.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "~2.7.1"
}
}
So after you've run sudo npm link you can run doto from anywhere, if you want to change the name of the executable just change the key under "bin" to whatever you prefer.
I tried npm link and it still was not working from my test package.
My package.json in the linked package had "directories": { "bin": "./bin" } instead of "bin": { "etc": "./etc.js" }.
Once I changed it back to "bin": {...} it started to work in the test package.
So, although this directories: { bin: ... } setting is documented it doesn't seem to work correctly with npm link.

Categories