I created a node script which checks if my project contains lock file or not. If it doesn't then I want to abort my npm build. Any idea how to do that?
lock-check.js
const path = require('path');
const fs = require("fs");
const lockFiles = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock"];
let exists = 0;
function checkIfExists() {
lockFiles.forEach(
(lf) => {
if (fs.existsSync(lf)) {
exists++;
}
});
return exists > 0;
}
package.json
...
"scripts": {
"prestart": "node ./lock-check.js" // Abort the task
"start": "webpack-dev-server --config config/webpack.dev.js --hot --inline"
}
...
To abort the build process you just have to call process.exit(1),
Here I have used 1 but you can use any non-zero exit code to tell it wasn't a successful build as 0 means successful.
You can read more on official nodejs docs
Related
If my Nexs.js app is started with
yarn dev
Where package.json defines it as
{
"scripts": {
"dev": "next dev -p 4000"
}
}
How I get this 4000 value from the -p switch?
Because process.env.PORT is not set this way.
const getBaseUrl = () => {
if (typeof window !== 'undefined') return ''; // browser use relative path
// How to replace the ???? with the value of -p, defaulting to 3000 if not set
return 'http://localhost:????'; // dev SSR should use localhost
}
I have a shell script which gives the commit hash and I want to run npm version and would like to concatenate with the hash.
So putting the shell command in js file and running with node works. Since the command is very short I want to run inline.
This works
npm --no-git-tag-version version $(node bump.js)
But would like to run in one line
npm --no-git-tag-version version+ git rev-parse --short HEAD
Here is my bump.js file
const shell = require('shelljs');
const { version } = require('../package.json');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// npm --no-git-tag-version version $(node config/bump.js)
// Ex: npm --no-git-tag-version version "10.1.6-develop-80a3053"
let commitHash = '';
if (commitHash = shell.exec('git rev-parse --short HEAD', { silent: true })) {
// Getting the base version from package.json
const baseVersion = version.match(/[\d+]{1,}\.[\d+]{1,}\.[\d+]{1,}/)[0];
// Concatenating base-version with develop-commit-hash
const hashedVersion = `${baseVersion}-develop-${commitHash}`;
shell.echo(`npm --no-git-tag-version version ${hashedVersion}`, { silent: true });
}
shell.exit(0);
I am using the Detox Test tool, and I am having difficulties.
I only installed Detox, I only ran the basic code for the ios test, and I get the following error:
Please help me.
Just iOS
Error Log
$ detox test --configuration ios.sim.debug --debug-synchronization --take-screenshots all --record-videos nonex --record-logs all
node_modules/.bin/jest e2e --config=e2e/config.json --maxWorkers=1 --testNamePattern='^((?!:android:).)*$'
FAIL e2e/firstTest.spec.js
● Test suite failed to run
ReferenceError: before is not defined
3 | const adapter = require('detox/runners/mocha/adapter');
4 |
> 5 | before(async () => {
| ^
6 | await detox.init(config);
7 | });
8 |
at Object.<anonymous> (init.js:5:1)
package.json
"script":{
"e2e:ios": "detox test --configuration ios.sim.debug --debug-synchronization --take-screenshots all --record-videos nonex --record-logs all",
"e2e:android": "detox test --configuration android.emu.debug --loglevel verbose --take-screenshots all --record-videos none --record-logs all"
},
dependencies": {
"detox": "^8.0.0",
"jest": "^23.1.0",
"mocha": "^5.2.0",
},
"detox": {
"configurations": {
"ios.sim.debug": {
"binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/{app_name[enter image description here][1]}.app",
"build": "xcodebuild -workspace ios/{workspace_Name}.xcworkspace -scheme {scheme_name} Dev -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
"type": "ios.simulator",
"name": "iPhone 7"
},
"android.emu.debug": {
"binaryPath": "android/app/build/outputs/apk/dev/debug/{apk_name}.apk",
"build": "react-native run-android --variant=devDebug --appId com.noahclient.dev",
"type": "android.emulator",
"name": "Nexus_5X_API_26"
}
},
"test-runner": "jest"
}
}
I looks like you are trying to run a mocha test on the jest runner. As your init.js is setup for mocha but the test runner that you are using is jest. This is confirmed by the error message node_modules/.bin/jest e2e... that you are getting.
You should pick either one, jest or mocha and use it. Rather than trying to use both.
#Jest
If you are using jest your init.js should look like this:
const detox = require('detox');
const config = require('../package.json').detox;
const adapter = require('detox/runners/jest/adapter');
jest.setTimeout(120000);
jasmine.getEnv().addReporter(adapter);
beforeAll(async () => {
await detox.init(config);
});
beforeEach(async () => {
await adapter.beforeEach();
});
afterAll(async () => {
await adapter.afterAll();
await detox.cleanup();
});
and you should add "test-runner": "jest" to the detox object in your package.json.
You should also have a config.json file in the same location as the init.js containing:
{
"setupFilesAfterEnv" : ["./init.js"]
}
#Mocha
If you are using mocha then your init.js should look like this:
const detox = require('detox');
const config = require('../package.json').detox;
const adapter = require('detox/runners/mocha/adapter');
before(async () => {
await detox.init(config);
});
beforeEach(async function () {
await adapter.beforeEach(this);
});
afterEach(async function () {
await adapter.afterEach(this);
});
after(async () => {
await detox.cleanup();
});
and you should remove the "test-runner": "jest" from the detox object in your package.json as it is not required.
Instead of a config.json file you should have a mocha.opts file beside your init.js and it should have something similar to:
--recursive
--timeout 120000
--bail
#Next steps
Choose the test runner that you are wanting to run; either jest or
mocha.
Make sure you have the correct init.js file for the test runner.
If using jest have a config.json file and add the test-runner to the detox object in the package.json.
If using mocha have a mocha.opts file. No need to specify a test-runner in the detox object in the package.json.
You can see the setup instructions here: https://github.com/wix/detox/blob/master/docs/Introduction.GettingStarted.md#step-3-create-your-first-test
If you are still having issues let me know.
"name": "javascript-development-environment",
"version": "1.0.0",
"description": "CS 235 package.json file for programming projects",
"scripts": {
"prestart": "babel-node buildScripts/startMessage.js",
"redditImgGet": "babel-node buildScripts/srcReddit.js",
"install": "npm install",
"start":"npm-run-all --parallel security-check open:src",
"security-check": "nsp check",
"open:src": "babel-node buildScripts/srcServer.js"
},
This is currently my package.json. I am trying to call the script which obtains an image from reddit. The inside of srcReddit.js is shown below:
var snoowrap = require('snoowrap');
console.log("Starting Reddit Image Fetcher");
const otherRequester = new snoowrap({
userAgent: navigator.userAgent,
clientId: 'Cf8kGqDSuT17xw',
clientSecret: 'DDmMslUwMJW1ZM5JTc07zJDpC8k',
username: 'sharan100',
password: 'Magewindu100'
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
r.getHot().map(post => post.title).then(console.log);
console.log("Ending Reddit Image Fetcher");
For this, I am using the wrapper snoowrap for the reddit API. Now when I do a npm start, I for some reason get this below:
No idea why the console.log messages do not appear. Does anyone know why?
npm start runs the start task and it does not refer to the redditImgGet task at any time, it seems.
I assume you should change your start task to
npm-run-all --parallel security-check open:src redditImgGet
Or just run the task directly
npm run redditImgGet
Otherwise, I don't see where you could expect the srcReddit file to log anything.
Background
I am very new to Node.js so please don't hate..
I found NPM very useful because I can install Node.js packages globally and then use them like standalone, available-on-path apps.
This does work on Windows, which really suprises me.
For instance I installed UglifyJS this way, via npm install -g uglifyjs and now I can run it from anywhere in my system, from the console via uglifyjs <rest of command> (not node uglifyjs .. or sth else).
I'd like to create my own stand-alone Node.js application. How do I get starded? I am asking here because most tutorials only cover how to write a simple script and then run it va node (which I already covered)
My current config
package.json:
{
"name": "hash",
"version": "1.0.0",
"author": "Kiel V.",
"engines": [
"node >= 0.8.0"
],
"main": "hash.js",
"dependencies": {
"commander" : "1.2.0"
},
"scripts": {
"start": "node hash.js"
}
}
hash.js:
var crypto = require('crypto'),
commander = require('commander');
/* For use as a library */
function hash(algorithm, str) {
return crypto.createHash(algorithm).update(str).digest('hex');
}
exports.hash = hash;
/* For use as a stand-alone app */
commander
.version('1.0.0')
.usage('[options] <plain ...>')
.option('-a, --algorithm [algorithm]', 'Hash algorithm', 'md5')
.parse(process.argv);
commander.args.forEach(function(plain){
console.log( plain + ' -> ' + hash(commander.algorithm, plain) );
});
Question:
Suppose I have only these two files in node-hash directory. How do I install this project, so that later I can run it in cmd.exe via hash -a md5 plaintext just like coffescript, jslint etc. installs ?
You have to add some code into package.json and hash.js, then you can run this command to install the package from local folder.
npm install -g ./node-hash
package.json
{
"name": "hash",
"version": "1.0.0",
"author": "Kiel V.",
"engines": [
"node >= 0.8.0"
],
"bin": {
"hash": "hash.js"
},
"main": "hash.js",
"dependencies": {
"commander" : "1.2.0"
},
"scripts": {
"start": "node hash.js"
}
}
hash.js
#!/usr/bin/env node
var crypto = require('crypto'),
commander = require('commander');
/* For use as a library */
function hash(algorithm, str) {
return crypto.createHash(algorithm).update(str).digest('hex');
}
exports.hash = hash;
/* For use as a stand-alone app */
commander
.version('1.0.0')
.usage('[options] <plain ...>')
.option('-a, --algorithm [algorithm]', 'Hash algorithm', 'md5')
.parse(process.argv);
commander.args.forEach(function(plain){
console.log( plain + ' -> ' + hash(commander.algorithm, plain) );
});