I'm Trying to log the location of tweets in a seperate JSON File for each Twitter ID i watch. The following code is called for each tweet and should create a new JSON File for each new ID and append the location of the current tweet:
console.log("#" + tweet.user.screen_name + " - " + tweet.user.name);
timeStampNow = "[" + date.getDate() + ":" + date.getMonth() + ":" + date.getFullYear() + "-" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]";
console.log(timeStampNow + " " + tweet.place.full_name);
fs.exists(userData + "/" + tweet.user.id + ".json", function(exists) {
//Is executed if file does not Exists
if (!exists){
console.log("Person Not Recognised. Adding to Folder");
json = {};
json.user = tweet.user;
json.locations = [];
fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(json), 'utf8', function(err) {
if (err) throw err;
console.log('complete');
});
}
//Appends data to file
fs.readFile(userData + "/" + tweet.user.id + ".json", function (err, data) {
var readJSON = JSON.parse(data);
console.log(readJSON);
locationJSON = {};
locationJSON.time = timeStampNow;
locationJSON.geo = tweet.geo;
locationJSON.coordinates = tweet.coordinates;
locationJSON.place = tweet.place;
readJSON.locations.push(locationJSON);
fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(readJSON), 'utf8', function(err) {
if (err) throw err;
console.log('complete');
});
});
});
The First part of the Script functions without a problem, but the Part that should append the current location to the JSON File, sometimes makes files empty, resulting in an Error:
undefined
^
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at ReadFileContext.callback (C:\path\to\Program.js:44:29)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:257:13)
Heres a example of how the JSON should look in the end:
{
"user":{
"id":"877id920012",
"id_str":"id_str",
"name":"name",
"screen_name":"screen_name",
"location":"location",
"url":"url",
"description":"description",
"translator_type":"translator_type",
"protected":"protected",
"verified":"verified",
"followers_count":"followers_count",
"friends_count":"friends_count",
"listed_count":"listed_count",
"favourites_count":"favourites_count",
"statuses_count":"statuses_count",
"created_at":"created_at",
"utc_offset":"utc_offset",
"time_zone":"time_zone",
"geo_enabled":"geo_enabled",
"lang":"lang",
"contributors_enabled":"contributors_enabled",
"is_translator":"is_translator",
"profile_background_color":"profile_background_color",
"profile_background_image_url":"profile_background_image_url",
"profile_background_image_url_https":"profile_background_image_url_https",
"profile_background_tile":"profile_background_tile",
"profile_link_color":"profile_link_color",
"profile_sidebar_border_color":"profile_sidebar_border_color",
"profile_sidebar_fill_color":"profile_sidebar_fill_color",
"profile_text_color":"profile_text_color",
"profile_use_background_image":"profile_use_background_image",
"profile_image_url":"profile_image_url",
"profile_image_url_https":"profile_image_url_https",
"profile_banner_url":"profile_banner_url",
"default_profile":"default_profile",
"default_profile_image":"default_profile_image",
"following":"following",
"follow_request_sent":"follow_request_sent",
"notifications":"notifications"
},
"locations":[
{
"time":"time",
"geo":"geo",
"coordinates":"coordinates",
"place":{
"id": "id",
"url": "url",
"place_type": "place_type",
"name": "name",
"full_name": "full_name",
"country_code": "country_code",
"country": "country",
"bounding_box": {
"type": "type",
"coordinates": "coordinates"
},
"attributes": {}
}
}
]
}
fs.writeFile and read file are async operation. When you create file, it might also try to read the file which has not yet been created so you get undefined data. On the side note , check errors
console.log("#" + tweet.user.screen_name + " - " + tweet.user.name);
timeStampNow = "[" + date.getDate() + ":" + date.getMonth() + ":" + date.getFullYear() + "-" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]";
console.log(timeStampNow + " " + tweet.place.full_name);
fs.exists(userData + "/" + tweet.user.id + ".json", function(exists) {
//Is executed if file does not Exists
if (!exists){
console.log("Person Not Recognised. Adding to Folder");
json = {};
json.user = tweet.user;
locationJSON = {};
locationJSON.time = timeStampNow;
locationJSON.geo = tweet.geo;
locationJSON.coordinates = tweet.coordinates;
locationJSON.place = tweet.place;
json.locations = [locationJSON];
fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(json), 'utf8', function(err) {
if (err) throw err;
console.log('complete');
});
}else{
fs.readFile(userData + "/" + tweet.user.id + ".json", function (err, data) {
var readJSON = JSON.parse(data);
console.log(readJSON);
locationJSON = {};
locationJSON.time = timeStampNow;
locationJSON.geo = tweet.geo;
locationJSON.coordinates = tweet.coordinates;
locationJSON.place = tweet.place;
readJSON.locations.push(locationJSON);
fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(readJSON), 'utf8', function(err) {
if (err) throw err;
console.log('complete');
});
});
}
//Appends data to file
});
, before perform any operation.
I'm trying to create files based on current time and date inside a scheduler.
Here's what I've tried so far.
var logFileNameScheduler = schedule.scheduleJob('*/2 * * * *', function () {
let date_ob = new Date();
let date = ("0" + date_ob.getDate()).slice(-2);
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
let year = date_ob.getFullYear();
let hours = date_ob.getHours();
let minutes = date_ob.getMinutes();
var st = 'data';
logFileName = 'Error log report at : ' + date + "-" + month + "-" + year + " " + hours + ":" + minutes + '.txt';
fs.writeFile(logFilename, st, (err) => {
if (err) console.log(err);
console.log("Successfully Written to File.");
});
});
But it creates corrupted files. I can't open them.
I am calling a webapi using get method which will give json data and I am display as a table from that data. the code which I have given below is working fine. I got around 25 rows(dynamically" of data when I fit the service. this webpage will be refreshed using signalR. when any changes in DB immediately it should reflect in the webpage.
My question is if "" + item.TakeupType + "" value is "Completed" or "cancelled" this row background should change to gray color and after 2mins row should be remove from the webpage.
Note:
1) Only 22 rows should display on webpage in orderby asc Datetime.
2) Completed/cancelled items from DB should will display on the webpage for 2 mins and drop off.
My code :
Hide Expand Copy Code
//Webapi call - To load info status.
function LoadinfoStatus() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('x-api-key', '9024024A-024-485C024-6BC2024DA');
}
});
$.ajax({
type: "GET",
url: "https://mywebsites.net/version1/info/494",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
//Function to get DateFormat
function getFormattedDate(date) {
// debugger;
var inputdate = new Date(date);
var currentdate = new Date();
var strTime = getFormattedTime(inputdate);
var rngStrTime = getFormattedTime(add_minutes(inputdate, 5));
if (inputdate > currentdate) {
return inputdate.getDate() + '/' + (inputdate.getMonth() == 0 ? 12 : inputdate.getMonth()) + " " + strTime + " - " + rngStrTime;
}
else {
return strTime + " - " + rngStrTime;
//return day + "/" + month + " - " + strTime;
}
}
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes * 60000);
}
function getFormattedTime(inputdate) {
var day = inputdate.getDate();
var month = inputdate.getMonth() + 1;
var hours = inputdate.getHours();
var minutes = inputdate.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ampm;
}
$.each(data, function (i, item) {
var rows = "<tr ' " + (item.Count > 100 ? "data-id='" + item.orderId + "'" : "") + (item.TakeupType == "Cancelled" ? "style='background-color: gray; color: white'" : "") + " align= 'center' > " +
"" + "" + "" + "" +
"" + item.user.firstName + " " + item.user.lastName.charAt(0) + "." + "" +
"" + item.TakeupType + "" +
"" + (item.Count == undefined ? "$" + " " + 0 : "$" + " " + item.Count) + "" +
"" + getFormattedDate(item.TakeupTimeUtc) + "" +
"= 100 ? "style='background-color: darkorange; color: white'>***" : ">") + "" +
"";
var $tbody = $('tblOrders tbody');
$('#tblOrders').append(rows);
}); //End of foreach Loop
registerEvents();
// console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
}
I have tried many ways to make a live clock (with seconds) appear in a rendered table but it's not working propperly. The clock stays static, not showing second by second. I'm doing the following :
function myTable(){
var table = $('<table></table>');
table.append($('<tr>')
.append($('<td>')
.addClass('col2 data')
.attr('rowspan', '2')
.append($('<span>')
.attr('id', 'date_time')
)
)
)
$("#myDiv").html(table)
}
liveClock();
var liveClock = function () {
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
var setDateTime = function() {
$("#date_time").html(result);
return false;
};
var everySec = setInterval(setDateTime, 1000);
}
Your problem is that you're never updating result, so each time your code fires SetDateTime, it renders the same date in the table. Move these lines:
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
Into your setDateTime function.
I have checked out this thread and this one but it didn't really help me.
I have a ASP:CheckBox control shown below.
<asp:CheckBox ID="chbArchived" runat="server" Checked='<%# Bind("archived") %>' OnClick=changeExpirationDate() />
My JavaScript are follows:
<script type="text/javascript">
$(document).ready(function () {
//alert("got here");
$('.insDateTime').datetimepicker({
ampm: true
});
changeExpirationDate(){
var currentDate = new Date;
var futureDateTime = (currentDate.getMonth() + 4) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + formatAMPM(currentDate);
var expiredDateTime = (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + formatAMPM(currentDate);
var archivedCheckbox = document.getElementById('cphContent_fmvNewsEventList_chbArchived').checked;
if(archivedCheckbox == true)
{
document.getElementById('cphContent_fmvNewsEventList_txtExpirationDate').value = expiredDateTime;
}
else{
document.getElementById('cphContent_fmvNewsEventList_txtExpirationDate').value = futureDateTime;
}
};
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
};
});
</script>
The problem is I kept getting this JavaScript error "Uncaught ReferenceError: changeExpirationDate is not defined" when I clicked on the checkbox. Any suggestion/help is much appreciated.
});
changeExpirationDate(){ <-- where is the function declaration?
var currentDate = new Date;
aka
function changeExpirationDate () {
Change
changeExpirationDate(){
to
function changeExpirationDate(){
The first makes it look like you are trying to call it; the second defines it.
Okay, after looking at one more time, I found out it was a very stupid mistake. I forgot the "function" before the function name, changeExpirationDate(), thus, it was giving me this error.