InternJs, How to set base path on command line? - javascript

Details:
I have a directory structure like this.
myapp
root-one
-web
-app
-tests
root-two
-grunt
node_modules
.bin
intern-runner
selenium-standalone
intern
selenium-standalone
grunt-shell
Gruntfile.js
From my grunt file I am using shell npm to launch the selenium standalone server like so..
shell: {
intern : {
options: { stdout: true},
command: [
"cd node_modules/.bin",
"start selenium-standalone start",
"intern-runner config=tests/intern basePath=../../../../root-one/web"
].join('&&')
}
}
}
grunt.registerTask('intern', ['shell:intern']);
After running my grunt command grunt intern, selenium starts but I get the following error from intern-runner.
Error: Failed to load module tests/intern
from C:/myapp/root-two/grunt/node_modules/.bin/tests/intern.js
Now because I set the path (or so I thought) using basePath=../../../../root-one/web. I would have expected it to try to execute from C:/myapp/root-one/web/tests/intern.js instead of remaining in the .bin directory.
Question:
So really the question is. What is the proper way to set the basePath for intern-runner on the command line? Because this doesn't seem to work. And according to the docs...
You can also specify any valid configuration option as an argument on
the command-line.
Which leads me to believe I probably just have the syntax wrong.

Sounds like this doesn't quite work the way I was expecting it to. As discussed here: https://github.com/theintern/intern/issues/449
So for now the work around was to just install intern globally vs trying to run it locally out of my project. So instead I did..
npm install intern -g
With my project structure like so...
myapp
root-one
-web
-app
-tests
root-two
-grunt
node_modules
.bin
selenium-standalone
selenium-standalone
grunt-shell
Gruntfile.js
Basically just removed intern because it is installed globally now. Which is located at the following on windows..
C:\Users\user\AppData\Roaming\npm\node_modules\intern
And my Gruntfile has been changed too the following. After starting selenium I change directory back to the appropriate location to run the intern-runner command.
shell: {
intern : {
options: { stdout: true},
command: [
"cd node_modules/.bin",
"start selenium-standalone start",
"cd ../../../../root-one/web",
"intern-runner config=tests/intern
].join('&&')
}
}
}
grunt.registerTask('intern', ['shell:intern']);

Related

Run Jest tests only for current folder

I have Jest installed on my machine and typing jest from terminal results in tests from parent folers also getting executed. I want to run tests only from the current folder.
For e.g. if I go to c:/dev/app in terminal and type some-jest-command, it should only run files with .test.js present in the app folder. Currently, running jest command from app folder runs tests in parent folders too, which is not my desired behaviour.
By default, Jest will try to recursively test everything from whatever folder package.json is located.
Let's say you're in c:/dev/app, and your package.json is in c:. If your basic command to invoke Jest is npm test, then try with run npm test dev/app.
If you want to run the tests from a specific folder user the --testPathPattern jest flag. When setting up the npm script add the path to the folder as well. In your package.json add the flag in you npm scripts. Check the bellow code for an example.
"scripts": {
....
"test:unit": "jest --testPathPattern=src/js/tests/unit-tests",
"test:integration": "jest --testPathPattern=src/js/tests/integration"
....
},
If you want to watch as well for changes, use the watch flag:
{
...
"test:unit": "jest --watch --testPathPattern=src/js/tests/unit-tests",
...
}
After that open, the command line, change the directory where your project is and run the unit test.
npm run test:unit
or integration tests.
npm run test:integration
To only run testing in a specific directory and to coerce Jest to read only certain type of files(my example: 'ExampleComponent.test.js' with new Jest version #24.9.0 you must write exact "testMatch" in jest.config.json || package.json in "jest" part next "testMatch": [ "<rootDir>/src/__tests__/**/*.test.js" ],
This testMatch in my case hits all files with the prefix .test.js in tests/subdirectories/ and skips all other files like 'setupTest.js' and other .js files in 'mocks' subdirectory which is placed inside of 'tests' directory,so,my 'jest.config.json' looks like this
{
"setupFiles": [
"raf/polyfill",
"<rootDir>/setupTests.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"moduleNameMapper": {
"^.+\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
"testMatch": [
"<rootDir>/src/__tests__/**/*.test.js"
]
}
Just adapt to your needs 'testMatch' regex.
A little note: This is for jest#24.9.0 && enzyme#3.10.0 if it matters to anyone.
I hope it will be useful to someone, cheers all.
--package.json
"scripts": {
"test": "jest"
}
--jest.config.js
module.exports = {
"testMatch": [
"<rootDir>/tests/unit/*.test.js"
]
}
From the root of your project, you can run jest <substring of files> and it will only run the test files which have the substring you added.
$ jest /libs/components
> [PASS] /libs/components/button.tsx
yarn:
yarn test nameoffolder
npm:
npm test nameoffolder
For example, if you have a folder named widget and you only want to run the tests in the widget folder you would run this command.
yarn:
yarn test widget
npm:
npm test widget

uglifyjs-folder remove console.log & alert from minified files

I am minifying multiple files in a folder using uglifyjs-folder in npm package.json like :
"uglifyjs": "uglifyjs-folder js -eyo build/js"
It is working as intended & minify all files in folder.
I want to remove any console.log & alert while minify but not able to find any option with uglifyjs-folderhttps://www.npmjs.com/package/uglifyjs-folder
Please help.
Short Answer
Unfortunately, uglifyjs-folder does not provide an option to silence the logs.
Solution
You could consider writing a nodejs utility script which utilizes shelljs to:
Invoke the uglifyjs-folder command via the shelljs exec() method.
Prevent logging to console by utilizing the exec() methods silent option.
The following steps further explain how this can be achieved:
Install
Firstly, cd to your project directory and install/add shelljs by running:
npm i -D shelljs
node script
Create a nodejs utility script as follows. Lets name the file: run-uglifyjs-silently.js.
var path = require('path');
var shell = require('shelljs');
var uglifyjsPath = path.normalize('./node_modules/.bin/uglifyjs-folder');
shell.exec(uglifyjsPath + ' js -eyo build/js', { silent: true });
Note: We execute uglifyjs-folder directly from the local ./node_modules/.bin/ directory and utilize path.normalize() for cross-platform purposes.
package.json
Configure the uglifyjs script inside package.json as follows:
{
...
"scripts": {
"uglifyjs": "node run-uglifyjs-silently"
...
},
...
}
Running
Run the script as per normal via the command line. For example:
npm run uglifyjs
Or, for less logging to the console, add the npm run --silent or shorthand equivalent -s option/flag. For example:
npm run uglifyjs -s
Notes:
The example gist above assumes that run-uglifyjs-silently.js is saved at the top-level of your project directory, (i.e. Where package.json resides).
Tip: You could always store run-uglifyjs-silently.js in a hidden directory named .scripts at the top level of your project directory. In which case you'll need to redefine your script in package.json as follows:
{
...
"scripts": {
"uglifyjs": "node .scripts/run-uglifyjs-silently"
...
},
...
}
uglify-folder (in 2021, now?) supports passing in terser configs like so:
$ uglify-folder --config-file uglifyjs.config.json ...other options...
and with uglifyjs.config.json:
{
"compress": {
"drop_console": true
}
}
And all options available here from the API reference.

How to run a command line tool from node.js application

The title of my question is how to run a command line tool from a node.js application because I think an answer here will apply to all command line utilities installable from npm. I have seen questions related to running command line from node.js, but they don't seem to be working for my situation. Specifically I am trying to run a node command line utility similar to npm (in how it is used, but not its function) called tilemantle.
tilemantle's documentation shows installing tilemantle globally and running the program from the command line.
What I would like to do is install tilemantle locally as a part of a npm project using npm install tilemantle --save and then run tilemantle from inside my project.
I've tried `tilemantle = require('tilemantle'), but the index.js file in the tilemantle project is empty, so I think this won't help with anything.
I tried the project node-cmd
const cmd = require('node-cmd');
cmd.run('./node_modules/tilemantle/bin/tilemantle', 'http://localhost:5000/layer/{z}/{x}/{y}/tile.png', '-z 0-11', '--delay=100ms', '--point=37.819895,-122.478674', '--buffer=100mi'
This doesn't throw any errors, but it also just doesn't work.
I also tried child processes
const child_process = require('child_process');
child_process.exec('./node_modules/tilemantle/bin/tilemantle', 'http://localhost:5000/layer/{z}/{x}/{y}/tile.png, -z 0-11 --delay=100ms --point=37.819895,-122.478674 --buffer=100mi'
This also doesn't throw any errors, but it also doesn't work.
Is there a way to get this working, so that I can run tilemantle from inside my program and not need to install it globally?
Update
I can get tilemantle to run from my terminal with
node './node_modules/tilemantle/bin/tilemantle', 'http://localhost:5000/layer/{z}/{x}/{y}/tile.png', '--delay=100ms', '--point=37.819895,-122.478674', '--buffer=100mi', '-z 0-11'
If I run the following as suggested by jkwok
child_process.spawn('tilemantle', ['http://myhost.com/{z}/{x}/{y}.png',
'--point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'],
{ stdio: 'inherit' });
I am getting spawn tilemantle ENOENT and if I replace tilemantle with ./node_modules/tilemantle/bin/tilemantle.js I get spawn UNKNOWN
Based on jfriend00's answer it sounds like I need to actually be spawning node, so I tried the following
child_process.spawn('node', ['./node_modules/tilemantle/bin/tilemantle.js', 'http://myhost.com/{z}/{x}/{y}.png', '--point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'], { stdio: 'inherit' });
Which gives me the error spawn node ENOENT which seems strange since I can run it from my terminal and I checked my path variable and C:\Program Files\nodejs is on my path.
Just to check I tried running the following with a full path to node.
child_process.spawn('c:/program files/nodejs/node.exe', ['./node_modules/tilemantle/bin/tilemantle.js', 'http://myhost.com/{z}/{x}/{y}.png', '--point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'], { stdio: 'inherit' });
which runs without the ENOENT error, but again it is failing silently and is just not warming up my tile server.
I am running Windows 10 x64 with Node 6.11.0
You can install any executable locally and then run it with child_process. To do so, you just have to figure out what the exact path is to the executable and pass that path to the child_process.exec() or child_process.spawn() call.
What it looks like you ultimately want to run is a command line that does:
node <somepath>/tilemantle.js
When you install on windows, it will do most of that for you if you run:
node_modules\.bin\tilemantle.cmd
If you want to run the js file directly (e.g. on other platforms), then you need to run:
node node_modules/tilemantle/bin/tilemantle.js
Note, with child_process, you have to specify the actual executable which in this case is "node" itself and then the path to the js file that you wish to run.
This, of course, all assumes that node is in your path so the system can find it. If it is not in your path, then you will have to use the full path to the node executable also.
It looks like you are trying to capture the output of tilemantle from running a file rather than from the command line. If so, I did the following and got it to work.
Installed tilemantle and child_process locally into a new npm project as you did, and added the following into a file in that project.
// test.js file
var spawn = require('child_process').spawn;
spawn('tilemantle', ['http://myhost.com/{z}/{x}/{y}.png', '--
point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'], { stdio: 'inherit' });
Run it using node test.js inside the project.
I tried a bunch of the other options in this post but could only get the above one to print the progress along with other output. Hope this helps!
Many command line utilities come with a "programmatic" API. Unfortunately, tilemantle does not, which is why you are unable to require that module in your code.
You can, however, easily access a locally installed version of the CLI from npm scripts. I don't know anything about tilemantle, so I'll provide an example using the tldr command line tool. In your package.json:
{
"name": "my-lib",
"version": "1.0.0",
"scripts": {
"test": "tldr curl"
},
"dependencies": {
"tldr": "^2.0.1"
}
}
You can now run npm test from the terminal in your project as an alias for tldr curl.
Per this post, you can use the global-npm package to run npm scripts from your code:
const npm = require('global-npm')
npm.load({}, (err) => {
if (err) throw err
npm.commands.run(['test'])
})
And voila, you can now run the locally installed CLI programmatically(ish), even though it has not offered an API for that.

Node.js/Grunt - Can't run Grunt's watch - why?

I am trying to use the autoprefixer css post-processor. I am following a tutorial and have installed npm. Using a npm, I then installed grunt and autoprefixer inside my project root using that package.json file: https://github.com/nDmitry/grunt-autoprefixer/blob/master/package.json
Following the tutorial, I then created this Gruntfile.js inside my project root:
module.exports = function (grunt) {
grunt.initConfig({
autoprefixer: {
dist: {
files: {
'build/style.css': 'style.css'
}
}
},
watch: {
styles: {
files: ['style.css'],
tasks: ['autoprefixer']
}
}
});
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-watch');
};
After that the tutorial advises to use Grunt Watch using
./node_modules/.bin/grunt watch
Which results in
-bash: ./node_modules/.bin/grunt: No such file or directory
I also tried to navigate to the grunt folder inside my project, then it says
-bash: node_modules/grunt: is a directory
I also have a node_modules folder directly in my local user folder, but addressing that folder grunt also just tells me that its a folder.
Pleaser help me, why is this not working? I am willing to really learn grunt, but I am not even able to get started using the getting started guide...
Have you installed the grunt-cli? (npm install grunt-cli -g) What happens when you run grunt in your project root? The command you should be running is simply grunt watch, in your project root.
Edit: Your project root must also have a package.json file in which you define your development dependencies; e.g.
{
"name":"yourprojectname",
"version":"0.0.1",
"devDependencies":{
"grunt":"*",
"grunt-contrib-watch":"*",
"grunt-autoprefixer":"*"
}
}
if there is acutally a space in the executable name you need to put it in quotes
"./node_modules/.bin/grunt watch"
otherwise linux will run "./node_modules/.bin/grunt" with watch as a flag.
if that still doesn't work,
could be a few problems, either your ldconfig isn't updated, the files aren't set to executable, or the user you are trying to execute the command with doesn't have permission.
first try running "ldconfig" (just type and run it)
more info here
http://www.cyberciti.biz/tips/linux-shared-library-management.html
chmod -x the files to make them executable.
any luck?

Why is process.env.NODE_ENV undefined?

I'm trying to follow a tutorial on NodeJS. I don't think I missed anything but whenever I call the process.env.NODE_ENV the only value I get back is undefined. According to my research the default value should be development. How is this value dynamically set and where is it set initially?
process.env is a reference to your environment, so you have to set the variable there.
To set an environment variable in Windows:
SET NODE_ENV=development
on macOS / OS X or Linux:
export NODE_ENV=development
tips
in package.json:
"scripts": {
"start": "set NODE_ENV=dev && node app.js"
}
in app.js:
console.log(process.env.NODE_ENV) // dev
console.log(process.env.NODE_ENV === 'dev') // false
console.log(process.env.NODE_ENV.length) // 4 (including a space at the end)
so, this may better:
"start": "set NODE_ENV=dev&& node app.js"
or
console.log(process.env.NODE_ENV.trim() === 'dev') // true
For people using *nix (Linux, OS X, etc.), there's no reason to do it via a second export command, you can chain it as part of the invoking command:
NODE_ENV=development node server.js
Easier, no? :)
We ran into this problem when working with node on Windows.
Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.
var environment = process.env.NODE_ENV || 'development';
In a production environment, we would define it per the usual methods (SET/export).
You can use the cross-env npm package. It will take care of trimming the environment variable, and will also make sure it works across different platforms.
In the project root, run:
npm install cross-env
Then in your package.json, under scripts, add:
"start": "cross-env NODE_ENV=dev node your-app-name.js"
Then in your terminal, at the project root, start your app by running:
npm start
The environment variable will then be available in your app as process.env.NODE_ENV, so you could do something like:
if (process.env.NODE_ENV === 'dev') {
// Your dev-only logic goes here
}
in package.json we have to config like below (works in Linux and Mac OS)
the important thing is "export NODE_ENV=production" after your build commands below is an example:
"scripts": {
"start": "export NODE_ENV=production && npm run build && npm run start-server",
"dev": "export NODE_ENV=dev && npm run build && npm run start-server",
}
for dev environment, we have to hit "npm run dev" command
for a production environment, we have to hit "npm run start" command
In macOS for those who are using the express version 4.x.x and using the DOTENV plugin, need to use like this:
After installing the plugin import like the following in the file where you init the application:
require('dotenv').config({path: path.resolve(__dirname+'/.env')});
In the root directory create a file '.env' and add the varaiable like:
NODE_ENV=development
or
NODE_ENV = development
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
In UBUNTU use:
$ export NODE_ENV=test
install dotenv module ( npm i dotenv --save )
require('dotenv').config() //write inside the file where you will use the variable
console.log(process.env.NODE_ENV) // returns value stored in .env file
Must be the first require in app.js
npm install dotenv
require("dotenv").config();
In my case, I have a node app. The way I have structured it is that I have client folder and server folder. I had my .env file inline with these two folder. My server file needs the .env file. It was returning undefined because it did not live inside the server file. It was an oversight.
App
-client
-server
-.env
Instead I moved .env inside server file like so:
App
-client
-server
|-.env <---here
|-package.json
|-and the rest of the server files...
(before this - ofcourse have the dotenv npm package installed and follow its doc)
It is due to OS
In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:
"scripts": {
"start": "node app.js",
"dev": "nodemon server.js",
"prod": "NODE_ENV=production & nodemon app.js"
}
For windows
Also set up your .env file variable having NODE_ENV=development
If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)
const dotenv = require('dotenv');
dotenv.config({ path: './config/config.env' });
You can use the dotenv package from npm, here is the link: https://www.npmjs.com/package/dotenv
Which allows you to place all your configuration in a .env file
If you faced this probem in React, you need react-scripts#0.2.3 and higher. Also for other environment variables than NODE_ENV to work in React, they need to be prefixed with REACT_APP_.
For me, the issue was that I was using the pkg library to turn my app into an executable binary. In that case, the accepted solutions didn't work. However, using the following code solved my problem:
const NODE_ENV = (<any>process).pkg ? 'production' : process.env.NODE_ENV;
I found this solution here on GitHub.
In Electron Js
"scripts": {
"start": "NODE_ENV=development electron index.js",
},
If you define any function with the name process then that may also cause this issue.
Defining process.env.NODE_ENV in package.json for Windows/Mac/Linux:
Here's what worked for me on my Mac (MacBook Pro 2019, 16 inch, Big Sur):
"scripts": {
"build": "export NODE_ENV=prod || set NODE_ENV=prod&& npx eslint . && node --experimental-json-modules ./backend/app.js && gulp",
},
Using the export NODE_ENV=prod || set NODE_ENV=prod&& string may work in Windows and Linux but I haven't tested that.
If someone could confirm that would be great.
Unfortunately using the cross-env npm package did NOT work for me at all in my package.json file and I spend a long time on my Mac trying to make this work.
I also faced this issue.
I moved .env file to the root folder (not the project folder, a level higher) and it worked out.
Check it. it might help you as well
You can also set it by code, for example:
process.env.NODE_ENV = 'test';

Categories