package.json:
"scripts": {
"cpFile": cp ../template/index.js /src/view/home/
}
and I run:
npm run cpFile fileName.js
I want it to execute
cp ../template/index.js /src/view/home/fileName.js
but it doesn't work.
First of all you need quotes around your command
"scripts": {
"cpFile": "cp ../template/index.js /src/view/home/"
}
then if you need to pass in args, you will need to use the args delimiter
> npm run cpFile -- fileName.js
>> cp ../template/index.js /src/view/home/ "fileName.js"
probably not what you want
you can read about it here too:
> npm help run
Edit
you will probably need to pass in the whole path to get what you want.
"scripts": {
"cpFile": "cp ../template/index.js "
}
Then:
> npm run cpFile -- /src/view/home/fileName.js
The serialization of JSON doesn't work with functions, RegEx nor error-objects. In addition this is not a valide JSON format you have posted.
JSON starts and ends with a curly brace { } and you will need quotes around most names and values you created, except numeric values and booleans.
{ "scripts": { "cpFile": "cp ../template/index.js /src/view/home/" } }
There is also no method to run JavaScript without having plugins installed, like most browsers do.
Maybe curl can help to execute the script.
Related
I am new to Node.js. Recently, I am building a script as below:
"updateData": "node runFirstScript.js && node runSecondScript.js",
"build:desktop": "npm run updateData env1",
"build:mobile": "npm run updateData env2",
I am expecting runFirstScript.js and runSecondScript.js can get the parameters env1 and env2 while they are executed.
Instead of separating as below:
"updateData1": "node runFirstScript.js",
"updateData2": "node runFirstScript.js",
"build:desktop": "npm run updateData1 env1 && npm run updateData2 env1",
"build:mobile": "npm run updateData1 env2 && npm run updateData2 env2",
Is there any optimum solution for this?
Thanks
Just change && to &,here is the reason what each symbol mean:
& is to make the command run in background. You can execute more than one command in the background, in a single go. For eg: Command1 & Command2 & Command3
&& is to make following commands run only if preceding command succeeds.For eg: Lets say we have Command1 && Command2 && Command3. Command2 will only execute if Command1 succeed.
Bonus: ; which is useful in your daily productivity, You can run several commands in a single go and the execution of command occurs sequentially. For eg: Command1; Command2; Command3
I am trying to inject a json as an argument value within npm script, like this:
(https://medium.com/typeforms-engineering-blog/codeceptjs-puppeteer-setting-up-multiple-configurations-32d95e65adf2)
"scripts": {
"example": "bash -c 'cat ./sample.json | tr -d ' \t\n\r''",
"test:override": "codeceptjs run --steps --config ./codecept.conf.js --override <expecting_output_json_here_from_example_script>",
}
The first script command 'example' executes well and displays the output json correctly in the console (same as input):
{
"helpers":{
"Puppeteer":{
"url":"http://yahoo.com",
"show":false,
"windowSize":"1920x1080"
}
}
however, I couldn't find the way to pass it as an argument value for the --override in the "test:override" script
I have tried various StackOverflow questions/answers, however, I couldn't find a way to achieve it.
I am using Git Bash in VS Code in Win10.
Please suggest a solution/alternate approach or point me to the right document/SO question.
To the best of my knowledge and efforts, I believe that it is not a duplicate question.
So I'm using the package esm and module-alias, but it seems like esm does not register module-alias's paths.
Here's how I'm loading my server file:
nodemon -r esm ./src/index.js 8081
Here's the top of my index.js file:
import "module-alias/register"
import "#/setup"
import "#/setup" does not work whereas require("#/setup") does.
The problem is that esm tries to handle all import statements when parsing the file, before any other module gets loaded.
When processing import statements, it uses node's builtin require rather than the modified require created by module-alias
To fix this, you need to first load module-alias and then esm. This way, module-alias will get the chance to modify the require function before esm gets to do anything.
You can achive this by passing multiple -r parameters to node, but make sure module-alias comes first:
node -r module-alias/register -r esm index.js 8081
or with nodemon:
nodemon -r module-alias/register -r esm ./src/index.js 8081
You also need to remove the import "module-alias/register" from your code, since now it's loaded from the command line.
For me worked the following code:
package.json
"scripts": {
"dev": "pkill -f lib/serverIndex.js; NODE_ENV=development node lib/serverIndex.js",
lib/serverIndex.js
require = require('esm')(module/*, options*/);
require('module-alias/register');
module.exports = require("./server.js");
This problem has been plaguing me for years because I want to write good quality code that is shared between node & browser.
I finally found a system that works:
Place 'nesm.js' in the root of your project
[optional] Place the 'nesm' shell script in your path, make it executable
Run scripts with: 'nesm file_to_run.js' or 'node path/to/nesm.js -- file_to_run.js'
'nesm.js'
/*
* esm and module-alias do not play nicely together.
* this precise arrangement is the only way I found to make it work.
* you can run this from anywhere in your project hierarchy.
* you can use args, and use in npm scripts.
* encourage the node.js devs to make this work natively. ux matters.
* ---- CAVEATS
* will not work with "type":"module"
* ---- SETUP
* place 'nesm.js' in the root of your project
* [optional] place the 'nesm' shell script in your path, make it executable
* ---- USAGE
* > nesm file_to_run.js
* to run without the nesm shell script:
* > node path/to/nesm.js -- file_to_run.js
* to run with nodemon:
* > nodemon -- path/to/nesm.js -- file_to_run.js
*/
require = require('esm')(module); // eslint-disable-line no-global-assign
require('module-alias/register'); // must come after esm for some reason
let runNext;
for(const arg of process.argv) {
if(runNext) {
let filename = arg;
if(filename[0]!='.' && filename[0]!='/') filename = './'+filename;
require(filename);
break;
}
runNext = (arg=='--');
}
'nesm' shell script
#!/bin/bash
if [ -z $1 ]; then
echo "Node esm runner. Usage: nesm file_to_run.js"
exit 1
fi
baseDir=$( pwd )
while [ ! -f "$baseDir/nesm.js" ]; do
if [ ${#baseDir} -le 1 ]; then
echo "nesm.js not found in folder ancestry"
exit 1
fi
baseDir="$(dirname "$baseDir")"
done
file1=$(realpath $1);
node $baseDir/nesm.js -- $file1
There is another solution, initially found in this comment to solve the problem without even using module-alias.
I also made a repo to simplify this, check it here esm-module-alias
I'm trying to execute node-dev in a sublime text 3 build system. node-dev is in my path:
Yet when I run this build script:
{
"cmd": ["node-dev", "$file"],
"selector": "*.js"
}
I get this error, which also shows that npm is in my path.
yet when I run with the same build script using node instead of node-dev it executes just fine.
I've also tried to include the "path" variable pointing at the node-dev bin folder, which didn't help at all.
Any help would be appreciated. Thanks.
Following worked for me in Sublime Text 3 on Windows
Tools -> Build System -> New Build System...
Enter the below text in the new file
Save the file as "nodejs.sublime-build"
{
"shell_cmd": "node ${file}",
"selector" : "source.js"
}
Prerequisite is to have node.js installed
Sublime text docs:
https://www.sublimetext.com/docs/build_systems.html
shell
Optional. If true, cmd will be run through the shell (cmd.exe, bash…)
Try to add "shell : true
{
"cmd": ["node-dev", "$file"],
"selector": "source.js",
"windows" : {
"shell": true
}
}
The command is incorrect for Sublime Text 3 :)
This is one example of running node as build system:
{
"shell_cmd": "taskkill /F /IM node.exe & node ${file}"
}
Please note that the array-version doesn't work like in Sublime Text 2.
For macOS, this worked for me on Sublime Text 3:
{
"cmd": ["node","$file","$file_base_name"],
"working_dir": "${project_path:${folder}}",
"selector":"source.js"
}
Selector Note
My selector setting was:
"selector":"*.js"
and OdatNurd advised that:
The reason is that the selector is not correct; it doesn't match file
names, it matches syntax scopes (i.e. it's based on the syntax in use
regardless of file extension); changing it to source.js from *.js
should get it working.
If you are a windows user.
Try applying the following snippet
{
"selector": "source.js",
"cmd": ["C:\\Program Files\\nodejs\\node", "<", "$file"],
"windows": {
"shell": true
}
}
Save this as node.sublime-build file.
For more info you can refer to http://docs.sublimetext.info/en/latest/ for more.
I use Mocha to test my JavaScript stuff. My test file contains 5 tests. Is that possible to run a specific test (or set of tests) rather than all the tests in the file?
Try using mocha's --grep option:
-g, --grep <pattern> only run tests matching <pattern>
You can use any valid JavaScript regex as <pattern>. For instance, if we have test/mytest.js:
it('logs a', function(done) {
console.log('a');
done();
});
it('logs b', function(done) {
console.log('b');
done();
});
Then:
$ mocha -g 'logs a'
To run a single test. Note that this greps across the names of all describe(name, fn) and it(name, fn) invocations.
Consider using nested describe() calls for namespacing in order to make it easy to locate and select particular sets.
Depending on your usage pattern, you might just like to use only. We use the TDD style; it looks like this:
test.only('Date part of valid Partition Key', function (done) {
//...
}
Only this test will run from all the files/suites.
If you are using npm test (using package.json scripts) use an extra -- to pass the param through to mocha
e.g. npm test -- --grep "my second test"
EDIT: Looks like --grep can be a little fussy (probably depending on the other arguments). You can:
Modify the package.json:
"test:mocha": "mocha --grep \"<DealsList />\" .",
Or alternatively use --bail which seems to be less fussy
npm test -- --bail
Just use .only before 'describe', 'it' or 'context'. I run using "$npm run test:unit", and it executes only units with .only.
describe.only('get success', function() {
// ...
});
it.only('should return 1', function() {
// ...
});
run single test –by filename–
Actually, one can also run a single mocha test by filename (not just by „it()-string-grepping“) if you remove the glob pattern (e.g. ./test/**/*.spec.js) from your mocha.opts, respectively create a copy, without:
node_modules/.bin/mocha --opts test/mocha.single.opts test/self-test.spec.js
Here's my mocha.single.opts (it's only different in missing the aforementioned glob line)
--require ./test/common.js
--compilers js:babel-core/register
--reporter list
--recursive
Background: While you can override the various switches from the opts-File (starting with --) you can't override the glob. That link also has
some explanations.
Hint: if node_modules/.bin/mocha confuses you, to use the local package mocha. You can also write just mocha, if you have it installed globally.
And if you want the comforts of package.json: Still: remove the **/*-ish glob from your mocha.opts, insert them here, for the all-testing, leave them away for the single testing:
"test": "mocha ./test/**/*.spec.js",
"test-watch": "mocha -R list -w ./test/**/*.spec.js",
"test-single": "mocha",
"test-single-watch": "mocha -R list -w",
usage:
> npm run test
respectively
> npm run test-single -- test/ES6.self-test.spec.js
mind the -- which chains whatever text comes after it to the npm script
There are multiple ways by which you can do this.
If you just want to run one test from your entire list of test cases then, you can write only ahead of your test case.
it.only('<test scenario name>', function() {
// ...
});
or you can also execute the mocha grep command as below
mocha -g <test-scenario-name>
If you want to run all the test cases which are inside one describe section, then you can also write only to describe as well.
describe.only('<Description of the tests under this section>', function() {
// ...
});
If you have multiple test files & you wanted to run only one of then you can follow the below command.
npm test <filepath>
eg :
npm test test/api/controllers/test.js
here 'test/api/controllers/test.js' is filepath.
You can try "it.only"
it.only('Test one ', () => {
expect(x).to.equal(y);
});
it('Test two ', () => {
expect(x).to.equal(y);
});
in this the first one only will execute
Hi above solutions didn't work for me.
The other way of running a single test is
mocha test/cartcheckout/checkout.js -g 'Test Name Goes here'
This helps to run a test case from a single file and with specific name.
Looking into the doc, we see that simply using:
mocha test/myfile
will work. You can omit the '.js' at the end.
Using Mocha's --fgrep (or just -f) you can select tests containing string, for example:
mocha -f 'my test x'
will run all tests containing my test x in either it(), describe() or context() blocks.
For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.
describe('My Test Description', () => {
it('test case 1', () => {
// My test code
})
it('test case 2', () => {
// My test code
})
})
then run
yarn test -g "My Test Description"
or
npm run test -g "My Test Description"
Not sure why the grep method is not working for me when using npm test. This works though. I also need to specify the test folder for some reason.
npm test -- test/sometest.js
Consolidate all your tests in one test.js file and add a script in your package.json:
"scripts": {
"api:test": "node_modules/.bin/mocha --timeout 10000 --recursive api_test/"
},
Type this command in your test directory:
npm run api:test