Saturday, August 27, 2022

node.js: date-and-time offset = dateObj.getTimezoneOffset() TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')

 

>PROBLEM


Supposing using date-and-time lib:

  npm install date-and-time --save

  const date = require('date-and-time')


and the date returning the standard format, something like this (locale: Brazil):

obj.createdAt = 'Fri Aug 26 2022 21:14:34 GMT-0300 (Horário Padrão de Brasília)';


the compiler throws the following error:

  date-and-time offset = dateObj.getTimezoneOffset() 

  TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')



>SOLUTION


***WRONG

created_at: date.format(obj.createdAt, 'YYYY/MM/DD HH:mm:ss'),


>RIGHT

created_at: date.format(new Date(obj.createdAt), 'YYYY/MM/DD HH:mm:ss'),



>ENV

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Tuesday, August 16, 2022

javascript: TypeError: Cannot read properties of undefined

 


>PROBLEM


TypeError: Cannot read properties of undefined


>SOLUTION


This error may have many causes.

Here, it's shown a tricky one — cyclic reference, when one file references the other.

Check the example below:


>file1 - SecTools.js

const UserSvc = require('../../models/business/UserSvc');

static verifySToken(req) {

if (req === 'undefined' || req == null) return false;

let userStoken = UserSvc.stokenSvc[req.body.email];

//...

}


>file2: UserSvc.js

const SecTools = require('../security/SecTools');

myOtherfunction() {

user.token = SecTools.signWithJwt(user.email);

}

The SecTools has reference to UserSvc, and vice-e-versa.


Remove the cyclic reference to fix the issue.


>IMPORTANT NOTE

When it happens an error during runtime, the same message may happen.
For instance, if the code calls a persistence method that is not recognized (found), to debug the app try to comment previous operations before that method is called. There is a good probability that one operation before (above the call that fails) is throwing an exception that results with this message.
It happens with many compilers, for many programming languages.
Something "mad", unexpected, think about this hypotheses.
Do not take compiler messages as they were always possible to show the real problem that it is causing the issue.


>ENV

Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64


express: Error: Cannot find module ...code: 'MODULE_NOT_FOUND'

 


>PROBLEM

Express returns compilation error:


node:internal/modules/cjs/loader:488

      throw e;

      ^

node:internal/modules/cjs/loader:488
      throw e;
      ^

Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\
   express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
    at resolveExports (node:internal/modules/cjs/loader:482:14)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (M:\work\devcli_\javascript\jstopics\
       express\node_sequelize_ultering_ml40643\prj\models\security\SecTools.js:5:19)
    at Module._compile (node:internal/modules/cjs/loader:1101:14) {
  code: 'MODULE_NOT_FOUND',
  path: 'M:\\work\\devcli_\\javascript\\jstopics\\
      express\\node_sequelize_ultering_ml40643\\prj\\node_modules\\sequelize\\package.json'
}




 

>SOLUTION


The tip is in this line (red):

Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'

that means the class loader was not able to find a reference.
Check the require statements that contain the type.

In this example, it was found the mistake in this declaration:

const { Utils } = require('sequelize/types');



>ENV

Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64

Monday, August 8, 2022

java: javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at


 >PROBLEM

Attempt to send email fails returning the following message:

javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at


>SOLUTION

Since 05/30/2022 , you may lose access to apps that are using less secure sign-in technology.
To help keep your account secure, Google will no longer support the use of third-party apps or devices which ask you to sign in to 
your Google Account using only your username and password. 

To solve this issue, there are options available.
A fast approach is to use the "App Password" option that generates a new password for the application to get access.

Using this option, the only thing necessary is to replace the previous user's password in your java code with the new password generated.

Go to "Fix Problems", then "Use an App Password".
Follow by the pictures.















>Extra

Configuration used:

PROPS.put("mail.debug", "false");

PROPS.put("mail.smtp.port", "587");

PROPS.put("mail.smtp.auth", "true");

PROPS.put("mail.smtp.starttls.enable", "true");

PROPS.put("mail.smtp.host", "smtp.googlemail.com");

PROPS.put("mail.smtp.ssl.trust", "smtp.gmail.com");

PROPS.put("mail.smtp.ssl.protocols", "TLSv1.2");

PROPS.put("mail.smtp.host", "smtp.gmail.com");

session = Session.getInstance(PROPS, new javax.mail.Authenticator() {

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(SENDER, PASSWORD);

}

});


>ENV

Java (javax.mail)
Windows

Wednesday, August 3, 2022

angular/node.js: debugging "Warning: Module not found: Error: Can't resolve..."


 >PROBLEM


After installing MongoDB libs

npm i --save mongoose

npm install @types/mongoose --save-dev


-- used for MongoClient

npm install --save mongodb

npm install --save dotenv



Warning: Module not found: Error: Can't resolve


./node_modules/mongodb/lib/bson.js:12:9-28 - Warning: Module not found: Error: Can't resolve 'bson-ext' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:36:2-40 - Warning: Module not found: Error: Can't resolve 'kerberos' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:43:2-49 - Warning: Module not found: Error: Can't resolve '@mongodb-js/zstd' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:51:2-36 - Warning: Module not found: Error: Can't resolve 'snappy' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:54:75-105 - Warning: Module not found: Error: Can't resolve 'snappy/package.json' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/utils.js:1399:32-87 - Warning: Critical dependency: the request of a dependency is an expression

./node_modules/mongodb/lib/utils.js:1407:32-68 - Warning: Module not found: Error: Can't resolve 'mongodb-client-encryption' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'



>SOLUTION


Sometimes, we are not sure if the environment is consistent or not.

The issue reported here was caused by the last lib installed (mongodb) in the app's env.

If you want to check this, you may skip steps and go straight to the fourth approach topic, at the end.

If you do want to recheck your app's env, you may start from the 1st approach.

First of all, stop the application, and close the IDE (VSCode/Eclipse, etc.).


1. APPROACH


- try:

npm cach verify


Retest.


2. APPROACH


If the 1st step didn't work, try to unistall the last libs installed.

In this case, it was the following:


npm uninstall mongoose

npm uninstall  @types/mongoose

npm uninstall mongodb

npm uninstall dotenv


- do:

npm cach clean

or

npm cach clean --force


- reinstall them:


npm i --save mongoose

npm install @types/mongoose --save-dev

npm install --save mongodb

npm install --save dotenv


- do:

npm install


- restart the app.


3. APPROACH


If the 2nd step didn't work, remove all cache and node_modules, reinstalling the libs.


- alternatively install:

npm install node-gyp -g


- run:

npm cache clean --force

rm -Rf node_modules

npm install

npm cache verify


- restart the app.


4. APPROACH


If the 3rd step didn't work, probably it is some lib issue.

To discover the cause, the libs were tested one at a time.


To discover the cause, test the libs one at a time.

Making rollback, both libs were uninstalled.

The it was reinstalled mongoose and tested with minimal code.

Passed.

Then, it was installed MongoClient and tested with minimal code.

The issue returned.

To discover the cause, the code was commented and tested one statement at a time, restarting the app.

First:

import * as mongoDB from 'mongodb';

import * as dotenv from 'dotenv';

After, code was commented and the cause was this line:

    const client = new mongoDB.MongoClient('mongodb://localhost:27017/test');




NOTE:

Sometimes it is necessary to repeat the procedure of cleaning, uninstalling, and installing until the application starts successfully (remember to stop the app and close the IDE):

npm cache clean --force
npm uninstal ... (all the libs to be uninstalled - rollback)
npm install
restart the app


5. APPROACH - Version Issue? Solving the mystery

After identifying the cause through the tests performed, it was possible to try another version to solve the mysterious incompatibility. So, the previous version was uninstalled and replace by another one, in this case a version already working fine in another demo application.

Current version to be replaced:
"mongoose": "^6.5.0",

Uninstalling:
npm uninstall mongoose --no-save

Replacing:
npm install --save mongoose@^5.8.3

Restarting application: success.





6. FINAL TIPS

The compiler for certain kinds of problems returns messages that are not very helpful.
If you stick on the error messages, you get stuck because they have nothing to do with the real cause.
Do not wait for a kind message telling necessarily the real issue behind the exception because it is not always possible.
Checking the result, you will not see something like that:
"Please, fix my mongoose version... blah, blah, blah'.    :-)   :-|   




7. Rule of thumb

Having issues?
Think:

1. Is my environment healthy, stable, and consistent?
First, make sure of that.

2. Think about version conflict.
This is a complicated matter.
Too many libs, too many versions, lead to possible many conflicts.


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


tslint: expected call-signature: ... to have a typedef

 

>PROBLEM


Using typscript and TSLint, return the following message:

  expected call-signature: 'run1' to have a typedef


>SOLUTION


>BEFORE

  async run1() {

    await mongoose.connect('mongodb://127.0.0.1');

  }

>AFTER  

  async run1(): Promise<any> {

    await mongoose.connect('mongodb://127.0.0.1');

  }


>ENV

VSCode

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...