gulp task with gulp-run-command doesn't work properly - command-line

I'm trying to run json-server in a gulp task and I'm checking if the server runs, with the function portInUse.
Like this:
var gulputil = require('gulp-util')
var run = require('gulp-run-command').default
var gulp = require('gulp')
const args = [
'json-server --watch .\\src\\main\\app\\reactjs\\api\\db.json --port 3005'
]
var net = require('net');
var portInUse = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(port, '127.0.0.1');
server.on('error', function (e) {
callback(true);
});
server.on('listening', function (e) {
server.close();
callback(false);
});
};
gulp.task("initLocalJsonServer", function() {
portInUse(3005, function(returnValue) {
gulputil.log('1 ' + returnValue);
});
run(args);
portInUse(3005, function(returnValue) {
gulputil.log('2 ' + returnValue);
});
});
That command that is the value of args here, works as intended when I run it in command line, so there's nothing wrong with the command or json-server itself. If I run it, I get to see the json-server at localhost:3005
Now the output from the portInUse function indicates that the server starts, as the output is:
[10:33:56] 1 false
[10:33:56] 2 true
But if I go to localhost:3005 after the gulp tasks are done, I can't see any server running. What might be the reason?

Related

Protractor: commands in afterLaunch don't run

I'm trying to send an email out with results after tests have finished running.
When I put the sendgrid call in the onComplete section, then the email sends. However, the report is empty since it hasn't finished saving.
If I put the sendgrid call into the afterLaunch section, then the file is saved. However, it doesn't seem to run the sendgrid command.
This is the config that I am using:
var HtmlReporter = require ('protractor-jasmine2-html-reporter');
var browser = "chrome";
var environment = "dev";
var pname = "";
var pversion = "";
var dname = "";
var selenium_address = "http://localhost:4444/wd/hub";
var folder_name = (new Date()).toString().split(' ').splice(0,3).join('');
var report_folder = "./test/e2e/reports/" + folder_name + "_" + browser + "_" + environment + "/";
var reporter = new HtmlReporter({
savePath: report_folder,
takeScreenshots: false,
cleanDestination: true,
fileName: 'CE_Smoketest'
});
function test_function() {
var report = report_folder + 'CE_Smoketest.html'
var sendgrid = require('sendgrid')('xxxxx', 'xxxxxxxxx');
var email = new sendgrid.Email();
email.addTo("destination#mail.com");
email.setFrom("Smoketest#mail.com");
email.setSubject("Smoketest");
email.setHtml("Smoketest results");
email.addFile({filename: report});
sendgrid.send(email);
}
exports.config = {
//appium setup
seleniumAddress: selenium_address,
multiCapabilities: [
{
'browserName' : browser,
platformName : pname,
platformVersion : pversion,
deviceName: dname
}
],
getPageTimeout: 50000,
allScriptsTimeout: 50000,
jasmineNodeOpts: {
defaultTimeoutInterval: 50000,
isVerbose: true
},
onPrepare: function() {
jasmine.getEnv().addReporter(reporter);
},
onComplete: function(exitCode) {
test_function();
},
afterLaunch: function(exitCode) {
test_function();
}
}
Any ideas as to why afterLaunch doesn't send the email?
In afterLaunch methods, Webdriver instance have been shutdow(Not available). That's you code will get executed. Check description of afterLaunch() method below:
/**
* A callback function called once all tests have finished running and
* the WebDriver instance has been shut down. It is passed the exit
code
* (0 if the tests passed). afterLaunch must return a promise if you
want
* asynchronous code to be executed before the program exits.
* This is called only once before the program exits (after onCleanUp).
*/
Suresh is right, you must return a promise if you want asynchronous code to be executed before the program exits
Try this:
1- Declare new var
var q = require('q');
2- Refactor your afterLaunch
afterLaunch: function(exitCode) {
return q.fcall(function () {
test_function();
}).delay(1000);
}

Running gulp exec based on condition

I am working on ionic project integrated with gulp. How can run exec command based on condition?
I have tried following
var isIOSBuild = false;
if(args.iosBuild){
isIOSBuild = true;
console.log("Creating IOS Build...");
}
// Build application
gulp.task('ios_build', function (cb) {
gulp.src('', {read: false})
.pipe(gulpif(false,
exec(IOS_BUILD_COMMAND,
{
cwd : './',
maxBuffer: 1024 * 1024
},
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
})
));
});
Input: gulp -r
I have put up condition for running exec command still the IOS_BUILD_COMMAND is running. Unable to understand why this is happening...
Alternatively, you can call the gulp task with or without arguments and run the task internally on the argument condition.
I use yargs to make my life easier.
var args = require('yargs').argv;
gulp.task('some_task', function(){
if(args.condition){
// run your task
}
})
Call gulp like so: gulp some_task --condition=true or gulp some_task --condition=false
That allows you to maintain the condition outside of gulp

Setting up PostCSS

I am just trying to set up PostCSS and integrate it into my recent workflow. But somehow I don't seem to get it work.
I am using A Mac and gulp as a task runner.
This is the erro I get when starting my watch task:
TypeError: $.postcss is not a function
And this is what my gulpfile.js looks like:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
rename: {
'browser-sync': 'browserSync',
'gulp-postcss': 'postcss',
},
pattern: ['gulp-*', 'gulp.*', 'del', 'run-sequence', 'browser-sync'],
DEBUG: false
});
var targetPath = 'dist';
var useBrowserSync = $.util.env.browserSync || true;
gulp.task('sass', function(){
return gulp.src('src/scss/*.{scss,sass,css}')
.pipe($.postcss([
require('precss')()
], {syntax: require('postcss-scss')}))
.pipe(gulp.dest(targetPath + '/public/assets/css'))
.pipe( $.if( useBrowserSync , $.browserSync.stream() ) );
});
gulp.task('watch', ['sass'], function(){
if( useBrowserSync ){
$.browserSync.create();
$.browserSync.init({
proxy: 'localhost/my_project/dist/public/'
});
}
gulp.watch('src/scss/*.{scss,sass,css}', ['sass']);
});
What is going wrong?

Log in to Facebook with phantomjs - 302 issues?

I'm trying to write a phantomjs script to log in to my facebook account and take a screenshot.
Here's my code:
var page = require('webpage').create();
var system = require('system');
var stepIndex = 0;
var loadInProgress = false;
email = system.args[1];
password = system.args[2];
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
page.render('output.png');
});
},
function() {
console.log(document.documentElement.innerHTML);
},
function() {
phantom.exit();
}
]
setInterval(function() {
if (!loadInProgress && typeof steps[stepIndex] == "function") {
console.log("step " + (stepIndex + 1));
steps[stepIndex]();
stepIndex++;
}
if (typeof steps[stepIndex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 10000);
(Inspired by this answer, but note that I've upped the interval to 10s)
Called like so:
./phantomjs test.js <email> <password>
With output (filtering out the selfxss warnings from Facebook):
step 1
load started
load finished
Login submitted!
load started
load finished
step 2
<head></head><body></body>
step 3
test
complete!
(Note that the html output in step two is empty)
This answer suggests that there are problems with phantomjs' SSL options, but running with --ssl-protocol=any has no effect.
This appears to be a similar problem, but for caspar, not phantomjs (and on Windows, not Mac) - I've tried using --ignore-ssl-errors=yes, but that also had no effect.
I guessed that this might be a redirection problem (and, indeed, when I replicate this on Chrome, the response from clicking "Submit" was a 302 Found with location https://www.facebook.com/checkpoint/?next), but according to this documentation I can set a page.onNavigationRequested handler - when I do so in my script, it doesn't get called.
I think this issue is related, but it looks as if there's no fix there.

Node.js TCP client behaving differently from Netcat/Telnet

I am issuing newline-separated text commands to a custom protocol TCP server. In the example below I issue 2 commands and receive a response written back. It works as expected in telnet and netcat:
$ nc localhost 1234
command1
command2
theresponse
The same workflow is not working when connecting with Node.js:
var net = require('net');
var client = net.connect(1234, 'localhost');
client.on('data', function(data) {
console.log('data:', data.toString());
});
client.on('error', function(err) {
console.log('error:', err.message);
});
client.write('command1\n');
client.write('command2\n');
I would expect that after running this program I would see "data: theresponse" written to the console, however, nothing is ever printed. I have also tried performing the writes inside of the "connect" callback, but I have the same results. The curious thing is that when I try this in the Node REPL...it works:
$ node
> var net = require('net')
undefined
> var client = net.connect(1234, 'localhost')
undefined
> client.on('data', function(data) { console.log('data:', data.toString()); })
{ ... }
> client.write('command1\n')
true
> client.write('command2\n')
true
> data: theresponse
Anyone have ideas about this bizarre behavior?
Thanks.
-Scott
Without testing the code, I'm presuming it's the asynchronous nature of Node.js that's biting you. In the REPL the connection happens before you can type in another command. In your code above you are writing before you are connecting.
Change the above code to this:
var net = require('net');
var client = net.connect(1234, function(){
client.on('data', function(data) {
console.log('data:', data.toString());
});
client.on('error', function(err) {
console.log('error:', err.message);
});
client.write('command1\n');
client.write('command2\n');
});