"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.
Related
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
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.
Is it possible to use the Electron built in auto updater with Gitlab tags?
I have seen that you can use Electron with GitHub releases, via electron-builder, but I am not sure the same can be said with Gitlab, as the use of Github tokens is required.
If there is no option to use Gitlab, are the only other options (a) a self hosted squirrel server, or (b) github releases?
You can use a generic host which is the easiest method, see:
https://gist.github.com/iffy/0ff845e8e3f59dbe7eaf2bf24443f104
You can edit updates.json/yml to point to the gitlab release, and it will be no worse than a generic server. It won't check the gitlab credentials, though.
You can use Amazon S3 or Bintray, see:
https://github.com/electron-userland/electron-builder/wiki/Publishing-Artifacts
Google Compute claims that they can be setup to be compatible with S3, so you could probably use them as well.
You may be able to use Gitlab releases the same as Github using the git+ssh syntax. Haven't tested that, but see Install npm module from gitlab private repository
My working example
.gitlab-ci
variables:
VERSION_ID: '1.0.$CI_PIPELINE_ID'
stages:
- build
build:
image: slauta93/electron-builder-win
stage: build
artifacts:
paths:
- $CI_PROJECT_DIR/dist/*.*
script:
- sed "s/0.0.0/${VERSION_ID}/g" package.json > _package.json && mv _package.json package.json
- npm install && npm run build
main.js
// Inital app
const electron = require("electron");
const updater = require("electron-updater");
const autoUpdater = updater.autoUpdater;
...
///////////////////
// Auto upadater //
///////////////////
autoUpdater.requestHeaders = { "PRIVATE-TOKEN": "Personal access Token" };
autoUpdater.autoDownload = true;
autoUpdater.setFeedURL({
provider: "generic",
url: "https://gitlab.com/_example_repo_/-/jobs/artifacts/master/raw/dist?job=build"
});
autoUpdater.on('checking-for-update', function () {
sendStatusToWindow('Checking for update...');
});
autoUpdater.on('update-available', function (info) {
sendStatusToWindow('Update available.');
});
autoUpdater.on('update-not-available', function (info) {
sendStatusToWindow('Update not available.');
});
autoUpdater.on('error', function (err) {
sendStatusToWindow('Error in auto-updater.');
});
autoUpdater.on('download-progress', function (progressObj) {
let log_message = "Download speed: " + progressObj.bytesPerSecond;
log_message = log_message + ' - Downloaded ' + parseInt(progressObj.percent) + '%';
log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
sendStatusToWindow(log_message);
});
autoUpdater.on('update-downloaded', function (info) {
sendStatusToWindow('Update downloaded; will install in 1 seconds');
});
autoUpdater.on('update-downloaded', function (info) {
setTimeout(function () {
autoUpdater.quitAndInstall();
}, 1000);
});
autoUpdater.checkForUpdates();
function sendStatusToWindow(message) {
console.log(message);
}
...
package.json
{
"name": "electron-updater-gitlab",
"version": "0.0.0",
"main": "main.js",
"scripts": {
"start": "electron .",
"pack": "node_modules/.bin/electron-builder --dir",
"build": "node_modules/.bin/electron-builder --win",
"postinstall": "",
"install": "node-gyp install",
},
"build": {
"appId": "com.electron.app",
"publish": [
{
"provider": "generic",
"url": "https://gitlab.com"
}
],
"win": {
"target": [
"nsis"
],
"verifyUpdateCodeSignature": false
},
"mac": {
"category": "public.app-category.productivity",
"identity": "Mac Developer: username (XXXXXXXX)",
"target": [
"dmg"
]
},
"linux": {
"target": [
"AppImage"
]
}
},
"dependencies": {
"electron-updater": "^2.7.2"
},
"devDependencies": {
"electron": "1.6.11",
"electron-builder": "^19.16.2"
}
}
After considering the answers in this issue and others, I ended up using GitLab Pages to publish my build artifacts. This allowed me to make make the installer files freely available to everyone in my organization without opening up the repo to everyone.
.gitlab-ci.yml:
stages:
- test
- build
- deploy
test-app:
stage: test
image: node:lts-alpine
script:
- npm install
- npm run test:colors
electron-release-build:
only:
- master
stage: build
image: electronuserland/builder:wine
script:
- npm ci
- npm run package:publish
artifacts:
paths:
- electron-release/*.exe*
- electron-release/*.yml
expire_in: 1 month
pages:
stage: deploy
only:
- master
image: alpine:latest
dependencies:
- electron-release-build
script:
# Note that `public` already exists in this repo, and has an index.html to
# to act as a downloads page.
- cp electron-release/*.exe electron-release/*.blockmap electron-release/*.yml public
- EXE_FILENAME=$(find ./electron-release -maxdepth 1 -name "Maestro*.exe")
- EXE_BASENAME=$(basename "$EXE_FILENAME")
- sed -i "s/INSERT_FILE_NAME/${EXE_BASENAME}/g" ./public/index.html
artifacts:
paths:
- public
Relevant part of package.json:
{
"build": {
"asar": true,
"appId": "com.myapp.app",
"productName": "myapp",
"directories": {
"output": "electron-release"
},
"extraFiles": [
"build/icon.ico"
],
"detectUpdateChannel": false,
"publish": {
"provider": "generic",
"url": "https://myappgroup.pages.example.com/myapp"
},
"win": {
"target": "nsis",
"verifyUpdateCodeSignature": false,
"icon": "build/icon.ico"
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowElevation": true,
"allowToChangeInstallationDirectory": true
}
}
}
No changes were needed anywhere else.
This also simplified things a bit, since I don't think I could use the provider URL proposed in another answer due to permissions (https://gitlab.com/_example_repo_/-/jobs/artifacts/master/raw/dist?job=build 404s for me).
I've recently added end-to-end tests using Protractor to my AngularJS application. I've run the tests locally and they all pass, however when I commit to GitHub and Travis for CI most of the tests fail.
I've noticed that the failing tests are those that require routing to other states (I'm using Angular UI Router).
scenarios.js
describe('Test', function () {
beforeEach(function () {
browser.get('/');
})
it('should open the user page', function () {
//browser.get("/");
browser.sleep(3000);
var button = element(by.id('createSession'));
button.click().then(function () {
browser.sleep(3000);
expect(browser.getLocationAbsUrl()).toEqual("/user");
});
});
it('should create a session and add a user', function () {
//browser.get("/");
browser.sleep(3000);
var button = element(by.id('createSession'));
button.click();
browser.sleep(3000);
var input = element(by.id('username'));
input.sendKeys('Simona');
var joinButton = element(by.id('joinSession'));
joinButton.click();
browser.sleep(3000);
expect(element(by.id('addStart')).isPresent()).toBe(true);
});
it('should join an existing session', function () {
//browser.get("/");
browser.sleep(3000);
var inputSession = element(by.id('sessionId'));
inputSession.sendKeys('testing123');
var joinSessionBtn = element(by.id('enterSession'));
joinSessionBtn.click();
browser.sleep(3000);
var input = element(by.id('username'));
input.sendKeys('Simona1');
var joinButton = element(by.id('joinSession'));
joinButton.click();
browser.sleep(3000);
expect(element(by.id('addStart')).isPresent()).toBe(true);
});
it('should add user to active users', function () {
//browser.get("/");
browser.sleep(3000);
var inputSession = element(by.id('sessionId'));
inputSession.sendKeys('testing123');
var joinSessionBtn = element(by.id('enterSession'));
joinSessionBtn.click();
browser.sleep(3000);
var input = element(by.id('username'));
input.sendKeys('Simona');
var joinButton = element(by.id('joinSession'));
joinButton.click();
browser.sleep(3000);
var user = element(by.id('Simona'));
expect(user.isPresent()).toBe(true);
});
it('should not join a non-existing session', function () {
//browser.get("http://localhost:8000/");
browser.sleep(3000);
var inputSession = element(by.id('sessionId'));
inputSession.sendKeys('simonovaSesija');
var joinSessionBtn = element(by.id('enterSession'));
joinSessionBtn.click();
browser.sleep(3000);
var warning = element(by.id('warningSession')).isDisplayed();
expect(warning).toBe(true);
});
it('should add an anonymous user on empty username input', function () {
//browser.get("http://localhost:8000/");
browser.sleep(3000);
var inputSession = element(by.id('sessionId'));
inputSession.sendKeys('testing123');
var joinSessionBtn = element(by.id('enterSession'));
joinSessionBtn.click();
browser.sleep(3000);
var input = element(by.id('username'));
input.sendKeys('');
var joinButton = element(by.id('joinSession'));
joinButton.click();
browser.sleep(4000);
var user = element(by.id('Anonymous'));
expect(user.isPresent()).toBe(true);
});
});
protractor.conf.js
exports.config = {
allScriptsTimeout: 11000,
specs: [
"scenarios.js"
],
capabilities: {
"browserName": "chrome"
},
baseUrl: "http://localhost:8000/",
framework: "jasmine",
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
package.json
{
"name": "angular-seed",
"private": false,
"version": "0.0.0",
"description": "A starter project for AngularJS",
"repository": "https://github.com/angular/angular-seed",
"license": "MIT",
"devDependencies": {
"bower": "^1.7.7",
"http-server": "^0.9.0",
"jasmine-core": "^2.4.1",
"karma": "^0.13.22",
"karma-chrome-launcher": "^0.2.3",
"karma-firefox-launcher": "^0.1.7",
"karma-jasmine": "^0.3.8",
"karma-junit-reporter": "^0.4.1",
"protractor": "^3.2.2"
},
"scripts": {
"postinstall": "bower install",
"prestart": "npm install",
"start": "http-server -a localhost -p 8000 -c-1 ./app",
"pretest": "npm install",
"test": "karma start karma.conf.js",
"test-single-run": "karma start karma.conf.js --single-run",
"preupdate-webdriver": "npm install",
"update-webdriver": "webdriver-manager update",
"preprotractor": "npm run update-webdriver",
"protractor": "protractor e2e-tests/protractor.conf.js",
"update-index-async": "node -e \"var fs=require('fs'),indexFile='app/index-async.html',loaderFile='app/bower_components/angular-loader/angular-loader.min.js',loaderText=fs.readFileSync(loaderFile,'utf-8').split(/sourceMappingURL=angular-loader.min.js.map/).join('sourceMappingURL=bower_components/angular-loader/angular-loader.min.js.map'),indexText=fs.readFileSync(indexFile,'utf-8').split(/\\/\\/##NG_LOADER_START##[\\s\\S]*\\/\\/##NG_LOADER_END##/).join('//##NG_LOADER_START##\\n'+loaderText+' //##NG_LOADER_END##');fs.writeFileSync(indexFile,indexText);\""
},
"dependencies": {
"bower": "^1.7.9",
"express": "^4.14.0"
}
}
.travis.yml
language: node_js
node_js:
- '4.4'
addons:
firefox: "latest"
# blocklist
branches:
except:
- master
# safelist
branches:
only:
- dev
before_script:
- export CHROME_BIN=chromium-browser
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
- npm start > /dev/null &
- npm run update-webdriver
- sleep 1 # give server time to start
script:
- node_modules/.bin/karma start karma.conf.js --no-auto-watch --single-run --reporters=dots
- node_modules/.bin/protractor e2e-tests/protractor.conf.js
As you can see, I'm using angular-seed's Angular template.
Any suggestions on why this is happening?
It would be most helpful to know what kind of errors you're getting, but regardless, you've got a couple obvious culprits...
CI is running headless (ie. via XVFB), your local is not. The two will have different timing issues.
You have a lot of sleeps, which can cause your tests to behave differently on different environments (eg. CI vs. local). This is one of the reasons sleeps are bad. This would also lead me to believe your app is not Angular? If that is true, then it's better to handle any waits yourself. If that is not true, then why all the sleeps?
Hope that helps a bit.
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) );
});