How Can I Console.log countdownjs module via node.js - node.js

I'm using countdownjs module
, How Can I Console.log countdownjs for 3 days later, via node.js?

Here is a small example how you can use the countdown module:
var now = new Date();
var durationInDays = 3;
var durationInMilliseconds = (durationInDays * 24 * 60 * 60 * 1000);
var future = now.getTime() + durationInMilliseconds;
var countdownInfo = countdown(now, future);
// print it once
console.log(countdownInfo.toString());
// print it every 5 seconds
function repeatedPrint() {
setTimeout(function () {
// you have to provide a new start date to get updated information
countdownInfo = countdown(new Date(), future);
console.log(countdownInfo.toString());
repeatedPrint();
}, 5 * 1000);
}
repeatedPrint();

Related

Cannot read property 'query' of undefined - In Vanilla Chrome Extension [duplicate]

This question already has answers here:
"Cannot read property of undefined" when using chrome.tabs or other chrome API in content script
(4 answers)
Closed 2 years ago.
I'm trying to program a simplistic application that runs a timer in content.js, but also sends an alert of the web page url. After looking at the documentation, I came up with this:
content.js
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
function(tabs){
alert(tabs[0].url);
}
);
let message = "";
console.log("Death Timer Running...");
let body = document.getElementsByTagName("body")[0];
let div = document.createElement("DIV");
div.setAttribute("CLASS", "timer");
let text = document.createElement("P1");
text.setAttribute("ID", "myText");
text.setAttribute("CLASS", "timerText");
div.appendChild(text);
body.appendChild(div);
var endDate = new Date("Oct 07, 2085 16:37:52").getTime();
var myfunc = setInterval(function() {
// code goes here
var now = new Date().getTime();
var timeLeftSeconds = parseInt((endDate - now)/1000);
var timeLeftMinutes = parseInt(timeLeftSeconds/60);
var timeLeftHours = parseInt(timeLeftMinutes/60);
var timeLeftDays = parseInt(timeLeftHours/24);
var timeLeftYears = parseInt(timeLeftDays/365);
let secondsLeft = timeLeftSeconds;
var yearsLeft = timeLeftYears;
secondsLeft -= (yearsLeft * 365 * 24 * 60 * 60)
var monthsLeft = parseInt(secondsLeft/(60*60*24*30))
secondsLeft -= (monthsLeft * 60 * 60 * 24 * 30)
var daysLeft = parseInt(secondsLeft/(60*60*24))
secondsLeft -= (daysLeft * 60 * 60 * 24)
var hoursLeft = parseInt(secondsLeft/(60*60))
secondsLeft -= (hoursLeft * 60 * 60)
var minutesLeft = parseInt(secondsLeft/(60))
secondsLeft -= (minutesLeft * 60)
message = (yearsLeft.toString() + "y, " + monthsLeft.toString() + "mo, " + daysLeft.toString() + "d, " + hoursLeft.toString() + "h, " + minutesLeft.toString() + "mi, " + secondsLeft.toString() + "s")
console.log(message)
document.getElementById("myText").innerText = message;
}, 1000)
manifest.json
{
"manifest_version":2,
"name":"Death Timer",
"version":"0.1",
"description":"A timer that helps you put things into perspective.",
"permissions":[
"activeTab", "tabs"
],
"content_scripts": [
{
"matches":[
"<all_urls>"
],
"js":["content.js"],
"css":["content.css"]
}
]
}
The timer is working fine, however when I try to implement the retrieval of the active tab, I receive this this error:
Uncaught TypeError: Cannot read property 'query' of undefined
at content.js:2
Why would this be happening? I've looked at other SO posts which all had the same problem - but those appeared to be due to the accessing of outside resources. My app is vanilla, so this shouldn't be an issue.
The chrome.tabs API is only available in background and popup scripts. That's why it is returning tabs as undefined.
If you want to use the API, you can send a message from the content script to the background, which will use the tabs API, then send the result back to the content script.

CLUI - fancy progress bar in nodejs console - is there an easy way to update it?

There is an existing example that updates progress bar in place: https://github.com/nathanpeck/clui/blob/master/examples/progress.js (60 lines in total)
There is much simpler example directly in the readme: https://github.com/nathanpeck/clui/blob/master/README.md (4 lines only)
var clui = require('clui');
var Progress = clui.Progress;
var thisProgressBar = new Progress(20);
console.log(thisProgressBar.update(10, 30));
So I've added setInterval so that it updates the progress. I've also added line to clear the console and new console.log with each interval:
var clui = require('clui');
var Progress = clui.Progress;
var value = 50;
var thisProgressBar = new Progress(20);
console.log(thisProgressBar.update(value, 100));
var intervalId = setInterval(function() {
value++;
// console.log("Updated value: " + value);
process.stdout.write('\033c'); // clearing the console
console.log(thisProgressBar.update(value, 100));
if (value === 100) {
clearInterval(intervalId);
}
}, 500)
In the example with countdown spinner - https://github.com/nathanpeck/clui/blob/master/README.md#spinnerstatustext - I don't have to clear the console and do console.log.
Ideally I would like to do just thisProgressBar.update(value, 100) and the progress bar should be updated in place easily... Not sure my approach is good, and before I start replicating 60 lines solution I want to ask!
Opened GitHub issue as well for extra visibility: https://github.com/nathanpeck/clui/issues/22
Tried creating https://runkit.com/embed/umrs8pxg9geg demo but it is not real console.
You can use npm log-with-statusbar package. How about this:
var clui = require("clui");
var log = require("log-with-statusbar")();
var Progress = clui.Progress;
var value = 50;
var thisProgressBar = new Progress(20);
// console.log(thisProgressBar.update(value, 100));
log.setStatusBarText([thisProgressBar.update(value, 100)]);
var intervalId = setInterval(function() {
value++;
// console.log("Updated value: " + value);
log("Updated value: " + value);
// process.stdout.write('\033c'); // clearing the console
log.setStatusBarText([thisProgressBar.update(value, 100)]);
// console.log(thisProgressBar.update(value, 100));
if (value === 100) {
clearInterval(intervalId);
}
}, 500);

CronJob executing only once

I'm using CronJob for NodeJS https://github.com/kelektiv/node-cron
I don't understand why but my CronJob is running only once. It is supposed to run once every 10 seconds but after the first run it doesn't restart.
async function Job(moneda, condicion) {
console.log('init');
var res = await Analyzer.GetSpread(moneda);
var spread = res.MaxExchange.Bid/res.MinExchange.Ask;
console.log('Spread: ' + spread + 'Moneda: ' + moneda);
if (await condicion.CumpleCondicion(spread)){
var ids = await db.GetSuscripciones();
var mensaje = 'Spread: ' + spread.toFixed(3) + '\nMenor Ask: ' + res.MinExchange.Exchange + '--> ' + res.MinExchange.Ask + '\nMayor Bid: ' + res.MaxExchange.Exchange + '--> ' + res.MaxExchange.Bid;
for (var i = 0, len = ids.length; i < len; i++) {
bot.SendAlert(ids[i].id,mensaje);
}
}
console.log('end'); //this is reached
}
exports.Start = function(value){
condicionBTC = new condicionState('btc');
new CronJob('*/10 * * * * *', Job('btc',condicionBTC), null, true, 'America/Los_Angeles');
}
And this is printed in the console (only once)
init
Spread: 1.007141110114658 Moneda: btc
cumple condicion 1.007141110114658
end
If there's some exception stopping the cron job, where should I catch it so I can see what's going on?
I've added this
var job = new CronJob('*/10 * * * * *', Job('btc',condicionBTC), null, true, 'America/Los_Angeles');
setInterval(function(){ console.log(job.running); }, 3000);
and keeps printing true
Your cron pattern is wrong. According to https://github.com/kelektiv/node-cron :
"this library has six fields, with 1 second as the finest granularity."
Seconds: 0-59
Minutes: 0-59
Hours: 0-23
Day of Month: 1-31
Months: 0-11 (Jan-Dec)
Day of Week: 0-6 (Sun-Sat)
So your cron pattern is trying to run every 10th of a second, which is not possible.
Try replacing your cron pattern with '10 * * * * *'

Schedule task for every 4 hours in Node.js

How could I schedule a task to run after 4 hours using "node-schedule" in Node.js
Currently my code is as below but it isn't responding as expected.
var schedule = require('node-schedule');
var task = schedule.scheduleJob('* */4 * * *', function () {
console.log('Scheduled Task');
});
Your syntax creates a cron that runs every minute every 4 hours.
The syntax you are looking for is 0 */4 * * *. Wich executes ONCE every 4 hours.
You can test the cron syntax with the website http://crontab.guru
Another option setting your cron in node is using rules. See https://github.com/node-schedule/node-schedule
var cron = require('node-schedule');
var rule = new cron.RecurrenceRule();
rule.hour = 4;
rule.minute = 0;
cron.scheduleJob(rule, function(){
console.log(new Date(), 'Every 4 hours');
});
try this
var cron = require('node-schedule');
var rule = new cron.RecurrenceRule();
rule.hour = new cron.Range(0,23,4);
rule.minute = 0;
cron.scheduleJob(rule, function(){
console.log(new Date(), 'Every 4 hours');
});
new cron.Range(0,23,4); 4 is the optional step parameter

new Date() Scheduled Script returning UTC not local time

I have a function in my library to return the current date:
function currentDate(addDays) {
if (addDays == null||addDays == undefined) {
addDays = 0;
}
var currentdate = new Date();
var current = nlapiAddDays(currentdate,addDays);
var day = current.getDate();
var month = current.getMonth()+1
var year = current.getFullYear();
return day+'/'+month+'/'+year;
}
All works fine, until I run a scheduled script which utilises this function, at which point the date returned is UTC, not our local time. Is there a simplistic method of conversion within this function without the need for external libraries?
Here is a utils function that I've used for years.
function getCompanyDate(){
var currentDateTime = new Date();
var companyTimeZone = nlapiLoadConfiguration('companyinformation').getFieldText('timezone');
var timeZoneOffSet = (companyTimeZone.indexOf('(GMT)') == 0) ? 0 : new Number(companyTimeZone.substr(4, 6).replace(/\+|:00/gi, '').replace(/:30/gi, '.5'));
var UTC = currentDateTime.getTime() + (currentDateTime.getTimezoneOffset() * 60000);
var companyDateTime = UTC + (timeZoneOffSet * 60 * 60 * 1000);
return new Date(companyDateTime);
}
It uses your company's NetSuite settings and timezone. This will return the date in the correct timezone assuming your NetSuite settings are correct.
You could then essentially do:
function currentDate(addDays) {
if (addDays == null||addDays == undefined) {
addDays = 0;
}
var currentdate = getCompanyDate();
var current = nlapiAddDays(currentdate,addDays);
var day = current.getDate();
var month = current.getMonth()+1
var year = current.getFullYear();
return day+'/'+month+'/'+year;
}
Suitescript 2.0 version of #lez-yeoh getCompanyDate
function getCompanyDate(){
var currentDateTime = new Date();
var companyTimeZone = config.load({ type: config.Type.COMPANY_INFORMATION }).getText({ fieldId: 'timezone' });
var timeZoneOffSet = (companyTimeZone.indexOf('(GMT)') == 0) ? 0 : Number(companyTimeZone.substr(4, 6).replace(/\+|:00/gi, '').replace(/:30/gi, '.5'));
var UTC = currentDateTime.getTime() + (currentDateTime.getTimezoneOffset() * 60000);
var companyDateTime = UTC + (timeZoneOffSet * 60 * 60 * 1000);
return new Date(companyDateTime);
}
This is what I do but you consume usage units since you have to create record.
First I create a hidden custom Date/Time field. Then I use the following code.
var record = nlapiCreateRecord(<recordtype>);
record.setDateTimeValue(<fieldid>, nlapiDateToString(new Date(), 'datetimetz', 5);
var userDateTime = record.getFieldValue(<fieldid>);
The variable userDateTime should now be in the local time zone.
The nlapiSetDateTimeValue() API function will convert the date/time value to the user's timezone. Below is its syntax:
nlapiSetDateTimeValue(fieldId, dateTime, timeZone)
fieldId = Id of the date/time field.
dateTime = Date value to be converted.
timeZone = The timezone of the date being passed. If its a server side script, it is usually in Pacific so we pass the Olson value of 5.

Resources