Nodejs parameter resolution and printing - node.js

I am trying to debug my mobile website which is running on Nodejs.
In some part there are those lines:
var log_line = {accessCount: accessCount, x: x, time: t};
logstream.write(JSON.stringify(log_line));
Which are suppose to log parts of the users page request. The path is defined as app.get('/:x?.:y?.:z?', function(req, res){ ).
For some users this works fine, but for others in the log I only find a line saying "{"accessCount": 1, "time": "10/10/10"}". How is it possible? shouldn't it at least printed the x without anything beside it? what could cause this effect?

If x is undefined, it won't get printed:
> JSON.stringify({x:undefined})
'{}'

If you are looking for a solution to get over it. Change the code as
if (!x) {
x = "NOT_DEFINED" // or your own place holder value
}
var log_line = {accessCount: accessCount, x: x :, time: t};
or more terse would be
var log_line = {accessCount: accessCount, x: x ? x : "NOT_DEFINED", time: t};

Related

NodeJS using single quotes instead of double quotes in object [Answered]

[Answered by: Loulou BadWeed]
Hi #NickP. , did you stringify/serialize your payload before passing
it in the fetch body ? Does not seem the case from your example and I
don't think fetch does that for you. Try JSON.stringify(config) in the
body argument of the fetch function
I have a "small" problem.
I can't figure out, why nodejs uses single quotes for the string value instead of double quotes...
My Code
let config = {}
config["active"] = 1
config["domain"] = req.body.domain
config["mailboxes"] = req.body.mailboxes
config["defquota"] = req.body.defquota
config["maxquota"] = req.body.maxquota
config["quota"] = req.body.quota
config["restart_sogo"] = 10
console.log(req.body.domain)
console.log(config)
What I input:
{
"domain": "domain.tld",
"mailboxes": 10,
"defquota": 512,
"maxquota": 1024,
"quota": 10240
}
What I get:
{
active: 1,
domain: 'domain.tld',
mailboxes: 10,
defquota: 512,
maxquota: 1024,
quota: 10240,
restart_sogo: 10
}
The problem I have with this, is that the mailcow api doesn't like single quotes in the request body. :) Does anyone know, why this happens and can help me?
I tried replacing the single quotes with str.replace() or str.replaceAll(). But that didn't work. I tried using both types where I used the '' outside of the "".
I also already asked ChatGPT for help, but the results were just the replace and replaceAll...
PS: It's 4:30 AM when I wrote this. I'm not at 100% of my usual capacity. So please don't hate me for my question.

Weird Moment-Timezone Behavior | UTC-LT Converstion

I try to convert UTC Times to Local Times
I have this Script
var moment = require("moment-timezone");
var utcDateStart = moment.utc("2022-03-12").startOf("day");
var utcDateEnd = moment.utc("2022-03-12").endOf("day");
let ltDateStart = utcDateStart.clone().tz("Europe/Berlin").startOf("day").utc();
let ltDateEnd = utcDateEnd.clone().tz("Europe/Berlin").endOf("day").utc();
console.log(ltDateStart, ltDateEnd);
I get this result:
Moment<2022-03-11T23:00:00Z> Moment<2022-03-13T22:59:59Z>
But i expect this:
Moment<2022-03-11T23:00:00Z> Moment<2022-03-12T22:59:59Z>
I dont get it... Is this a bug? How can i achieve this? (without subtracting 1 day)

How is the context treated?

I have a weird behaviour on Core Data with my App. I have an App where user can create their own words entries with translation. When deleting all my Core Data I checked the nb of item and it was 0. When adding later 4 items the nb of items was 5?? I found the issue after a lot of tests and it seems not consistent for me: the issue was with this code:
fileprivate func duplicateCheckAndImport() {
// Check for duplicates
do {
self.words = try context.fetch(Word.fetchRequest()) // grab all Words
let nbOfWords = words!.count
print ("The nb of words in duplicateCheck...: \(nbOfWords ?? 0)")
}
catch {
// error message to add
}
let newWord = Word(context: self.context)
do {
self.words = try context.fetch(Word.fetchRequest()) // grab all Words
let nbOfWords = words!.count
print ("The nb of words in duplicateCheck...: \(nbOfWords ?? 0)")
}
catch {
// error message to add
}
the result of the 2 prints is 0 for the first grab and 1 for the 2nd grab which means that just this line of code -> let newWord = Word(context: self.context) adds an entry in Core Data but my purpose was just to take the context add words later on like this:
let newWord = Word(context: self.context)
newWord.name = item.name.trimmingCharacters(in: .whitespaces)
newWord.definition = item.definition.trimmingCharacters(in: .whitespaces)
Can someone explain me?
The line of code you mention
let newWord = Word(context: self.context)
...creates a new instance. That's what Word(context: self.context) does-- it says, create a new instance of Word using the context that you pass in.
From the code you provide, it's hard to tell exactly what you're trying to do that would not create a new instance. Your variable is called newWord, which suggests that you do mean to create a new Word, and that's what's happening.
Update: If you don't want the new instance, you can delete it just like any other managed object. So if you don't want newWord, you can
context.delete(newWord)
And then save changes. There are other ways to do this, but this is the simplest.

Str::limit laravel

I have a file name examples:
4030-2210201884140.jpg
527884197_w640_h640_1ff2cccdbed562cef696d0c7adf41292.jpg
need to do to so was:
4030-22...1884140.jpg
5278841...df41292.jpg
Been looking for a solution but could not find it.
I have visited the post
Cutting down a length of a PHP string and inserting an ellipses
But sometimes it may not fit for you try below function
I have converted your requirement to a function with default arguments:
function getFirstLast($string='527884197_w640_h640_1ff2cccdbed562cef696d0c7adf41292.jpg',$orgOnF=7,$orgOnB=-11,$maskedString='.',$maskRepeat=3)
{
if (strlen($string) <= 21)
{
return $string;
}
$firstPartString = mb_substr($string, 0 ,$orgOnF);
$secondPartString = mb_substr($string,$orgOnB);
$maskedString = str_repeat($maskedString, $maskRepeat);
$finalResult = $firstPartString.$maskedString.$secondPartString;
return $finalResult;
}
echo getFirstLast();

Groovy TimeCategory bad millseconds addition

When try this sample code:
use(groovy.time.TimeCategory) {
800.millisecond + 300.millisecond
}
in groovy web console, I get a funny result:
0.1100 seconds
Does any one know why this happens or how to fix it?
That looks like a bug, the TimeDuration contains 1100 milliseconds, but when it prints it out, it converts it wrongly to seconds.
I've added it to the Groovy JIRA as a bug EDIT It's now marked as FIXED for versions 2.0.6, 1.8.9 and 2.1.0
In the mean time, I guess you'll need to do your own converter from TimeDuration to String :-/
Edit
You could do something like this (and there is probably a neater way of doing it)
groovy.time.TimeDuration.metaClass.normalize = { ->
def newdmap = ['days','hours','minutes','seconds','millis'].collectEntries {
[ (it):delegate."$it" ]
}.with { dmap ->
[millis:1000,seconds:60,minutes:60,hours:24,days:-1].inject( [ dur:[ days:0, hours:0, minutes:0, seconds:0, millis:0 ], roll:0 ] ) { val, field ->
val.dur."$field.key" = dmap."$field.key" + val.roll
val.roll = val.dur."$field.key".intdiv( field.value )
val.dur."$field.key" = field.value < 0 ?
val.dur."$field.key" :
val.dur."$field.key" % field.value
val
}.dur
}
new TimeDuration( newdmap.days, newdmap.hours, newdmap.minutes, newdmap.seconds, newdmap.millis )
}
That adds a normalize method to TimeDuration, so then doing:
use(groovy.time.TimeCategory) {
800.millisecond + 300.millisecond
}.normalize()
Shows 1.100 seconds
I haven't done a huge amount of testing on that method, so be warned it could do with some unit tests to make sure it doesn't fall over with other situations.

Resources