iris2008 / iris2008.github.io

My Hexo Blog
0 stars 0 forks source link

NodeJs notes | Iris' Blog #9

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

NodeJs notes | Iris' Blog

dirnamedirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

https://iris2008.github.io/2020/12/09/NodeJs-notes/

iris2008 commented 3 years ago

npm audit failure

When you see the error from npm audit and saying vulnerabilities of modules used. You may have to check version of those module by google " npm" and find the latest version and then replace package.json with latest version. Another consideration is remove package-lock.json if using AWS build

iris2008 commented 3 years ago

npm test failure

When you run into issue like "npm update check failed" , you may want to delete the local config store file (C:\Users\userId.config\configstore file)and retry. It will fix the issue.

iris2008 commented 3 years ago

npm audit failure

First , try npm audit fix to see if that fixes the issue.

If you saw the error ""npm update check failed", try below

Go to C:\Users.config and deleted the "configstore" folder.

once I done this, next time a ran npm start, the folder was re-generated, and error stopped

iris2008 commented 1 year ago

Subaru Forester Maintenance List - 80,000KM

Inspect wheel bearings Inspect propeller shaft Inspect axle boot condition Inspect and adjust drive belt tension Inspect and adjust all fluid levels including both differentials Inspect all steering and suspension components Lubricate all latches, hinges and locks (hood, doors, fuel door and trunk lid) Test coolant, inspect hoses and clamps

iris2008 commented 1 year ago

AWS issue related to REST API call

If you always get error "malformed lambda response" , it may be caused by two issues:

  1. The format returned is not same as that defined in Swagger file
  2. You should use "JSON.stringfy" to return body, as below

let successResponse = { statusCode: 200, headers: headers, body: data, body: JSON.stringify(data), isBase64Encoded: false };

iris2008 commented 10 months ago

Why the information in your log is not in ELK

  1. In template, we must set 'LOGGING_LEVEL' , 'SERVICE_NAME' and 'STAGE' in Lambda Environment Variables
  2. In index.js , we have to use framework.execute() to run our own function, instead of run it directly
iris2008 commented 10 months ago

Key differences: SSL vs. TLS

While the purposes of SSL and TLS are very similar, these communication protocols are distinct in how they operate. These changes developed over time as SSL moved through various versions before it was succeeded by TLS.

SSL/TLS handshakes

A handshake is a process in which a browser authenticates a server’s SSL or TLS certificate. This process authenticates both parties, then exchanges cryptographic keys.

An SSL handshake was an explicit connection, while a TLS handshake is an implicit one. The SSL handshake process had more steps than the TLS process. By removing additional steps and reducing the total number of cipher suites, TLS has sped up the process.

Alert messages

Alert messages are how SSL and TLS protocols communicate errors and warnings. In SSL, there are only two alert message types: warning and fatal. A warning alert indicates that an error has occurred, but the connection can continue. A fatal alert indicates that the connection must be terminated immediately. Additionally, SSL alert messages are unencrypted.

TLS has an additional alert message type called close notify. The close notify alert signals the end of the session. TLS alerts are also encrypted for additional security.

Message authentication

Both SSL and TLS use message authentication codes (MACs), a cryptographic technique for verifying the authenticity and integrity of messages. By using a secret key, the record protocol generates the MAC as a fixed-length code and attaches it to the original message.

The SSL protocol uses the MD5 algorithm—which is now outdated—for MAC generation. TLS uses Hash-Based Message Authentication Code (HMAC) for more complex cryptography and security.

Cipher suites

A cipher suite is a collection of algorithms that create keys to encrypt information between a browser and a server. Typically, a cipher suite includes a key exchange algorithm, a validation algorithm, a bulk encryption algorithm, and a MAC algorithm. Several algorithms in TLS were upgraded from SSL due to security concerns.

iris2008 commented 10 months ago

How to parse response of node-fetch properly

You need to check the response type first and if it's success or failure

res = await fetch(url)
if (res.headers.get('content-type').includes('json')) {
  // it's json
  await res.json()
} else {
  // it's something else
  await res.arrayBuffer()
}
you could always get an arrayBuffer and use it for something else

res = await fetch(url)
buff = await res.arrayBuffer().then(Buffer.from)

try {
  JSON.parse(buff.toString())
} catch (err) {
  // not json
}

OR

tell if it's response success

if (response.ok) {
data = response.json();
}
else {
error = response.text()
}
iris2008 commented 10 months ago

NodeJS import or require ?

Remember, require is the established CommonJS syntax, while import is the newer ECMAScript standard. Both have their strengths and can coexist in a Node.js project, depending on the module system used and the compatibility of external packages.

Use import and require in the same file

Enabling ES import/export

You can use ES6 import/export in Node.js by simply adding "type": "module" to your package.json file, like this:

{ "type": "module" }

To use require in the ES module scope, you have to define it. Just two lines of code to get the job done:

// These lines make "require" available
import { createRequire } from "module";
const require = createRequire(import.meta.url);

Example :

Put the code below to your index.js:

// index.js
import express from "express";

// Define "require"
import { createRequire } from "module";
const require = createRequire(import.meta.url);

const data = require("./data.json");

const app = express();
app.use(express.json());
app.get("/", (req, res) => {
  res.status(200).send(data);
});

app.listen(3000, (error) => {
  if (error) {
    throw new Error(error);
  }

  console.log("Backend is running");
});

4. Gives your data.json some data:

{
  "name": "John Doe",
  "age": 101,
  "occupation": "astronaut"
}
iris2008 commented 9 months ago

Are PostgreSQL column names case-sensitive?

Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double quotes and thereby retained upper case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:

"first_Name" → "first_Name" -- upper-case "N" preserved "1st_Name" → "1st_Name" -- leading digit preserved "AND" → "AND" -- reserved word preserved But:

first_Name → first_name -- upper-case "N" folded to lower-case "n" 1st_Name → Syntax error! -- leading digit AND → Syntax error! -- reserved word

Values (string literals / constants) are enclosed in single quotes:

'xyz'

So, yes, PostgreSQL column names are case-sensitive (when double-quoted):

SELECT * FROM persons WHERE "first_Name" = 'xyz';

iris2008 commented 9 months ago

How to handle http error response from node-fetch

handleHTTPError : async function (response) {
    if (!response.ok) {
        console.log(response.headers.raw());
        console.log("iterate headers");
        for (let [key, value] of response.headers) {
            //it appeared that the error details was in headers of BOX response

            console.log(`${key} :  ${value}`);
        }
        console.log("raw: ");
        for (let h in response.headers.raw()) {

            console.log(response.headers.raw()[h]);
        }
      let  message = `(${response.status}) ${response.statusText}\n\n`;
      for (let [key, value] of response.headers) {
        //it appeared that the error details was in headers of BOX response
        message +=  `${key} :  ${value}`;

    }
      let  headers = (response.headers['_headers'] != undefined && Object.keys(response.headers['_headers']).length > 0 )  ? response.headers['_headers'] : 
      ((response.headers['headers'] != undefined && Object.keys(response.headers['headers']).length > 0 )  ? response.headers['headers'] : response.headers);

      console.log(headers);
      console.log(headers.raw());
      ulog.info("response headers: " , headers);

      let errorMsg = await response.arrayBuffer().then(Buffer.from);

      ulog.info("stream response: ", await errorMsg.toString());

      throw new Error(message);
    }
    return response;
  },