I have a the following script:
function execute(){
require("fs").readFile("sometextfile.txt", function(err, cont) {
if (err)
throw err;
console.log("ALERT:"+(cont.indexOf("mystring")>-1 ? " " : " not ")+"found!");
});
}
setInterval(execute,9000);
I want to execute a javascript only if the string contains "Alert: found!"
The script:
var Prowl = require('node-prowl');
var prowl = new Prowl('API');
prowl.push('ALERT', 'ALERT2', function( err, remaining ){
if( err ) throw err;
console.log( 'I have ' + remaining + ' calls to the api during current hour. BOOM!' );
});
Help!
Are you asking how to combine the two?
const fs = require('fs');
const Prowl = require('node-prowl');
const prowl = new Prowl('API');
function alert() {
prowl.push('ALERT', 'ALERT2', function(err, remaining) {
if (err) throw err;
console.log('I have ' + remaining + ' calls to the API during current hour. BOOM!');
});
}
function poll() {
fs.readFile('sometextfile.txt', function(err, cont) {
if (err) throw err;
if (cont.indexOf('mystring') !== -1) {
alert();
}
});
}
setInterval(poll, 9000);
Related
I am trying to query a flight api with my async queue in node but it appears as my queue never "drains" (simply run the drain method). I am using this library.
It runs every request just fine but then it just stops there and the content in the drain function never executes.
let flights = [];
let q = async.queue(function (airline, callback) {
const flight_search_url = 'http://someflightapi.com/search/' + airline.code + '?date=' + date + '&from=' + originAirportCode + '&to=' + destinationAirportCode;
request(flight_search_url, function(error, response, body) {
if (error) {
return callback(error);
}
if (res.statusCode !== 200) {
return callback(res.statusCode);
}
console.log(airline.code);
flights.push(JSON.parse(body));
callback();
});
}, 10);
q.drain(function(error) {
if (error) {
res.json({
error: "There was an error while calculating flights",
destinationAirportCode: destinationAirportCode,
originAirportCode: originAirportCode,
possibleOrigins: possibleOrigins,
possibleDestinations: possibleDestinations,
flights: flights
});
} else {
res.json(flights);
}
});
q.push(airlines);
I have a code like this written in node.js for aws applications. I'm familiar with java and python but not with javascript.
I need to check if i have any messages left in my queue and if so i need to proccess them then delete. But as far as i understand the while loop doesn't wait for my queue processes and just run. After some time it exhausts my memory.
If i do it with for loop then no problem but i must do this with while loop so is there any way to use while loop for this?
message_count = true;
while (message_count === true)
{
queue.getQueueAttributes(params_queue, function (err, data)
{
if (err)
console.log(err, err.stack);
else
console.log(data);
if (data.Attributes.ApproximateNumberOfMessages == "0")
{
message_count = false;
}
queue.receiveMessage(function (err, data)
{
if (data)
{
message = data.Messages[0].Body
receipthandle = data.Messages[0].ReceiptHandle;
params.ReceiptHandle = receipthandle
queue.deleteMessage(params, function (err, data)
{
if (err)
console.log(err, err.stack);
else
console.log(data);
});
}
});
});
}
Here is some sample code I wrote sometime back to consume messages from queue. And when there are no messages try again after 1 minute delay.
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
AWS.config.update({region: 'us-east-1'});
var sqs = new AWS.SQS();
var sqsQueueURl = "<queueurl>";
var receiveMessageParams = {
QueueUrl : sqsQueueURl,
MaxNumberOfMessages : 10,
VisibilityTimeout : 10,
WaitTimeSeconds : 10
};
var receiveMessage = function() {
sqs.receiveMessage(receiveMessageParams, function(err, data) {
if(err){
console.log(err);
}
if (data.Messages) {
for (var i = 0; i < data.Messages.length; i++) {
var message = data.Messages[i];
var body = JSON.parse(message.Body);
// execute logic
removeFromQueue(message);
}
receiveMessage();
} else {
setTimeout(function() {
receiveMessage()
}, 60 * 1000);
}
});
};
var removeFromQueue = function(message) {
sqs.deleteMessage({
QueueUrl : sqsQueueURl,
ReceiptHandle : message.ReceiptHandle
}, function(err, data) {
err && console.log(err);
});
};
receiveMessage();
I'm using Node to run this program, where is my error(s)? It's saying I'm missing ) after argument list. I can't find where this error is, I've tried putting the ) in various places. I'm using Node v5
var Twit = require('twit');
var T = new Twit(require('./config.js'));
var stream = T.stream('statuses/filter', {
track: 'xoxo, oi, i\m fine,'
});
(stream.on('tweet', function(tweet) {
console.log('#' + tweet.user.screen_name + ': ' + tweet.text);
if (tweet.text.indexOf('RT') > -1) {
return;
}
var replyString;
if (tweet.user.utc_offset === null) {
replyString = ' Ok';
} else {
replyString = ' Okay';
}
})
(T.post('statuses/update', {
status: '#' + tweet.user.screen_name + replyString,
in_reply_to_status_id: tweet.id_str
}, function(err, data, response) {
if (err) {
console.log(err);
return;
}
}
tweet.botReplyId = data.id_str);
db.tweets.insert(tweet);
});
(end)
})
setInterval(stream, 60000);
The code seems to be a bit all over the place with regards to scope and it makes it a bit difficult to follow.
Try using something like the following which annotates it a bit and should help avoid issues like this (as it seems to validate without any errors) :
// Define your variables
var Twit = require('twit');
var T = new Twit(require('./config.js'));
var stream = T.stream('statuses/filter', { track: 'xoxo, oi, i\'m fine,'});
// When a tweet occurs
(stream.on('tweet', function(tweet) {
// Log it
console.log('#' + tweet.user.screen_name + ': ' + tweet.text);
// Determine if it is a retweet and ignore
if (tweet.text.indexOf('RT') > -1) { return; }
// Set your reply
var replyString = (tweet.user.utc_offset === null) ? ' Ok' : ' Okay';
// Post your reply
T.post('statuses/update', { status: '#' + tweet.user.screen_name + replyString, in_reply_to_status_id: tweet.id_str}, function(err, data, response) {
// If an error occurs, log it
if (err) {
console.log(err);
return;
}
// Otherwise store your response and store it
tweet.botReplyId = data.id_str;
db.tweets.insert(tweet);
});
}));
// Check your stream every 10 minutes
setInterval(stream, 60000);
//Server Functions
var socketArray = [];
var socketRcon = [];
for (var i = 0; i < serversConfig.serversArray.length; i++) {
socketArray[i] = new Socket;
socketArray[i].setEncoding("utf8");
socketArray[i].setNoDelay();
socketArray[i].setTimeout(1000);
socketArray[i].connect(serversConfig.serversArray[i].port, serversConfig.serversArray[i].ip);
socketRcon[i] = serversConfig.serversArray[i].rcon;
socketArray[i].on("connect", function() {
this.write(socketRcon[i] + "\n", "utf8");
console.log("CONNECTED TO THE SERVER...");
});
socketArray[i].on("data", function(data) {
console.log(data);
});
socketArray[i].on("error", function(err) {
console.log("ERROR:" + err);
});
socketArray[i].on("close", function(err) {
console.log("CLOSED:" + err);
});
};
This is the code I have now to connect to multiple servers from a config file, and I need that each time the socket connects, I need to send a password to it. But 'socketRcon[i]' is undefined, why is that happening and how do i fix it?
Because by the time that code is run, i is equal to serversConfig.serversArray.length, meaning socketRcon[i] is undefined.
Anchor your value:
for( var i=0; i<l; i++) (function(i) {
// do stuff here
})(i);
You could also just do:
serversConfig.serversArray.forEach(function(srvconfig) {
var sock = new Socket();
sock.setEncoding("utf8");
sock.setNoDelay();
sock.setTimeout(1000);
socketArray.push(sock);
socketRcon.push(srvconfig.rcon);
sock.on("connect", function() {
this.write(srvconfig.rcon + "\n", "utf8");
console.log("CONNECTED TO THE SERVER...");
});
sock.on("data", function(data) {
console.log(data);
});
sock.on("error", function(err) {
console.log("ERROR:" + err);
});
sock.on("close", function(err) {
console.log("CLOSED:" + err);
});
sock.connect(srvconfig.port, srvconfig.ip);
});
I am using node-phantom to post items to a cart on a web site. The problem is that when I use page.open to navigate to the shopping cart page (after already having added an item to the cart), I get an html response saying that I need to enable javascript in my browser in order to view the shopping cart page. I've checked the settings.javascriptEnabled setting and found it to be set to 'true'. At this point I am confused, why does the page think that phantomjs does not have javascript enabled?
Here is my code:
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.get('settings', function(err, oldSettings) {
console.log('\r\n oldSettings: ' + JSON.stringify(oldSettings));
page.open('http://www.somesite.com/shoppingcart/default.cfm', function (err, status) {
page.injectJs(jqueryPath, function (err) {
setTimeout(function() {
page.evaluate(function (injectedSku) {
var localErr;
var skuInCart;
var checkoutLnkMsg;
var pageHTML;
try {
pageHTML = $("html").html();
// Get 'SKUs' input element.
skuInCart = $('input[name="SKUs"]').val();
if (injectedSku === skuInCart) {
var checkoutLnk = $('#cartAction_bottom a[alt="Checkout"');
checkoutLnk.on("click", function() {
checkoutLnkMsg = '"' + checkoutLnk.href + '" link has been clicked';
});
checkoutLnk.click();
} else {
throw new Error('Product not in cart');
}
} catch (e) {
localErr = e;
}
return {
pageHTML: pageHTML,
err: localErr,
skuInCart: skuInCart,
checkoutLnkMsg: checkoutLnkMsg,
injectedSku: injectedSku
};
}, function (err, result) {
if (result.err) {
callback(err);
//return ph.exit();
}
fs.writeFileSync("./html_log.txt", result.pageHTML);
console.log('\r\n checkout - page.evaluate - injectedSku: ' + result.injectedSku);
console.log('\r\n checkout - page.evaluate - result.skuInCart: ' + JSON.stringify(result.skuInCart));
console.log('\r\n checkout - page.evaluate - result.checkoutLnkMsg: ' + result.checkoutLnkMsg);
callback(null);
//return ph.exit();
}, sku);
}, 1250);
});
});
});
});
});
Replace
page.injectJs()
with
page.includeJs()
UPDATE
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.get('settings', function(err, oldSettings) {
//console.log('\r\n oldSettings: ' + JSON.stringify(oldSettings));
page.open('http://www.footlocker.com/shoppingcart/default.cfm?', function (err, status) {
console.log(status);
var sku = 234; // assign sku id here
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js', function (err) {
setTimeout(function() {
page.evaluate(function (injectedSku) {
var localErr;
var skuInCart;
var checkoutLnkMsg;
var pageHTML;
try {
pageHTML = $("html").html();
// Get 'SKUs' input element.
skuInCart = $('input[name="SKUs"]').val();
if (injectedSku === skuInCart) {
var checkoutLnk = $('#cartAction_bottom a[alt="Checkout"');
checkoutLnk.on("click", function() {
checkoutLnkMsg = '"' + checkoutLnk.href + '" link has been clicked';
});
checkoutLnk.click();
} else {
throw new Error('Product not in cart');
}
} catch (e) {
localErr = e;
}
return {
pageHTML: pageHTML,
err: localErr,
skuInCart: skuInCart,
checkoutLnkMsg: checkoutLnkMsg,
injectedSku: injectedSku
};
}, function (err, result) {
if (result.err) {
// callback(err);
//return ph.exit();
}
// fs.writeFileSync("./html_log.txt", result.pageHTML);
console.log('\r\n checkout - page.evaluate - injectedSku: ' + result.injectedSku);
console.log('\r\n checkout - page.evaluate - result.skuInCart: ' + JSON.stringify(result.skuInCart));
console.log('\r\n checkout - page.evaluate - result.checkoutLnkMsg: ' + result.checkoutLnkMsg);
// callback(null);
ph.exit();
}, sku);
}, 1250);
});
});
});
})
});