Search This Blog

2023/07/29

Worker Thread in Node.js

 index.js


const {Worker} = require("worker_threads");

let number = 10;
const worker = new Worker("./myWorker.js", {workerData: {num: number}});

worker.once("message", result => {
console.log(`${number}th Fibonacci No: ${result}`);
});

worker.on("error", error => {
console.log(error);
});

worker.on("exit", exitCode => {
console.log(`It exited with code ${exitCode}`);
})

console.log("Execution in main thread");

-------------------------------------------------------------------------


myWorker.js

const { parentPort, workerData } = require("worker_threads");

parentPort.postMessage(getFibonacciNumber(workerData.num))

function getFibonacciNumber(num) {
if (num === 0) {
return 0;
}
else if (num === 1) {
return 1;
}
else {
return getFibonacciNumber(num - 1) + getFibonacciNumber(num - 2);
}
}

Output:
Execution in main thread 10th Fibonacci No: 55 It exited with code 0

2023/07/26

BigInt in javascript

 BigInt values represent numeric values which are too large to be represented by the number

It is created by appending n to the end of an integer literal,
or by calling the BigInt() function
e.g.
const bigIntNumber = 1n;


A BigInt value cannot be used with methods in the built-in Math
object and cannot be mixed with a Number value in operations;
they must be coerced to the same type. however, as the precision of
a BigInt value may be lost when it is coerced to a Number value.

typeof 1n === "bigint"; // true
typeof BigInt("1") === "bigint"; // true


A BigInt value can also be wrapped in an Object:

typeof Object(1n) === "object"; // true

Comparision:

0n === 0; // false different types
0n == 0; // true


Sorting:
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
mixed.sort((a, b) => a - b);

sorting using previous function won't work since subtraction will
not work with mixed types

You will get follwoing error:
TypeError: can't convert BigInt value to Number value


How to sort mixed array with bigInt

mixed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));


The following operators may be used with BigInt values or object-wrapped
BigInt values:

+ * - % **


Also unsupported is the unary operator (+),

Here consider following code

var x = 1n
var y = 5
console.log(y - x)

we get error as
TypeError: Cannot mix BigInt and other types, use explicit conversions


with explicit conversion

var x = 1n
var y = 5
console.log(BigInt(y) - x)

output:
4n

Negative BigInt

Consider following code

var x = -1n
var y = 5
console.log(BigInt(y) - x)

Output:
6n

AND & OR Logical Operator on Truthy & False values

// If the first operand is falsy, the logical AND operator returns that object.

//and operator
console.log("1:",false && "dog");
console.log("2:",0 && "dog");

//here first operand is truthy
console.log("1.1:","dog" && false);
console.log("2.1:","dog" && "0");

// Output:
// 1: false
// 2: 0
// 1.1: false
// 2.1: 0

// If the first operand is truthy, the logical AND operator returns the second operand.

console.log("3:",true && "dog")
console.log("4:",[] && "dog")

//here also first operand is truthy

console.log("3.1:","dog" && true)
console.log("4.1:","dog" && [])

// Output:
// 3: dog
// 4: dog
// 3.1: true
// 4.1: []

// If the first operand is falsy, the logical OR operator returns the second operand.

//or operator
console.log("5:",false || "dog");
console.log("6:",0 || "dog");

//here first operand is truthy
console.log("5.1:","dog" || false);
console.log("6.1:","dog" || 0);

// Output:
// 5: dog
// 6: dog
//5.1: dog
//6.1: dog

// If the first operand is truthy, the logical OR operator returns that object.

console.log("7:",true || "dog")
console.log("8:",[] || "dog")

//here first operand is truthy
console.log("7.1:", "dog" || true)
console.log("8.1:", "dog" || [])

// Output:
// 7: true
// 8: []
// 7.1: dog
// 8.1: dog

Truthy & Falsy Values in javascript

 In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context.

below are truthy values.if evaluated in if clause it will return true.

true
{}
[]
42
"0"
"false"
new Date()
-42
12n
3.14
-3.14
Infinity
-Infinity

e.g.

if("0"){
console.log("True")
}
else{
console.log("False")
}
output:
True

A falsy (sometimes written falsey) value is a
value that is considered false when encountered in a Boolean context.

Following are falsy values in javascript

null
undefined
false
NaN
0
-0
0n
""

e.g.

if ("") {
console.log("True")
}else{
console.log("False")
}

output:
False

How to check number is integer

 var num1 = 123


if(num1 % 1 ==0){
console.log("It's Integer")
}

Output:
It's Integer

2023/07/25

FizzBuzz Challenge

 What is FizzBuzz?


FizzBuzz is a task where the programmer is asked to print numbers from 1 to 100,
but heres the catch, multiple of three should printFizzand similarly printBuzzfor multiples of 5
and lastly printFizzBuzzfor multiples of three and five.


for (let i = 1; i < 101; i++) {
if (i % 15 == 0) {
console.log("FizzBuzz")
}
else if (i % 5 == 0) {
console.log("Buzz")
}
else if (i % 3 == 0) {
console.log("Fizz")
}
else {
console.log(i)
}
}

Closure triple multiplication

 


function mul(x){
return function(y){
return function(z){
return x*y*z;
}
}
}

var res = mul(2)(3)(4)

console.log(res)

output:
24

Check number is integer or not

 var num = 23.678


if(num == Math.floor(num)){
console.log("Integer")
}else{
console.log("Not An Integer")
}

if(num == Math.ceil(num)){
console.log("Integer")
}else{
console.log("Not An Integer")
}

output:
Integer Integer



How to emply array

 var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];


console.log("Before:",arrayList)

arrayList.splice(0,arrayList.length)

console.log("After:",arrayList)

output:
Before: [ 'a', 'b', 'c', 'd', 'e', 'f' ] After: []

How to check object is an Array

 var arrayList = [1, 2, 3];


if (Object.prototype.toString.call(arrayList) == '[object Array]') {
console.log("It is an array")
} else {
console.log("It is not an array")
}

if (Array.isArray(arrayList)) {
console.log("It is an array")
} else {
console.log("It is not an array")
}

Output:
It is not an array It is not an array


How to reverse each word in sentence

 var sentence = "Welcome to this Javascript Guide!";

var splitted = sentence.trim().split(/\s+/)

var reversed = splitted.map((word)=>{
return word.split("").reverse().join("")
})

var reversedSentence = reversed.join(" ")

console.log(reversedSentence)

output:
emocleW ot siht tpircsavaJ !ediuG

Split string over multiple white spaces

 var sentence = " I am sangram desai. "

var arr = sentence.trim().split(/\s+/)
console.log(arr)

output:

[ 'I', 'am', 'sangram', 'desai.' ]

2023/07/22

yarn vs npm

 Yarn and npm are both popular package managers in the JavaScript ecosystem,

used to manage dependencies and packages for Node.js and front-end projects.

Here's a comparison of the two:

Performance:

Yarn was developed by Facebook and was designed to be faster and more
efficient than npm.
In the past, Yarn's performance was noticeably better, but npm has since
improved its
performance in recent updates. The difference in performance may not be as
significant
as it once was, but Yarn is still generally considered to be slightly faster
in most cases.

Dependency Resolution:

Yarn uses a deterministic algorithm for dependency resolution, meaning that
the same
package versions will be installed across different environments. This helps
ensure
consistency among team members and on different machines.
npm 5.x and later versions introduced a new package-lock.json file,
which improved npm's dependency resolution and made it more deterministic
like Yarn.
Offline Mode:

Yarn has a built-in offline caching feature that allows you to install
packages
without an internet connection if they were previously downloaded. This is
useful
for scenarios where you need to work in a limited or no-network environment.
npm also supports an offline mode by using the cache stored on your machine,
but it requires a separate package (npm-offline) to be installed.

CLI (Command Line Interface):

The Yarn CLI is more user-friendly and provides additional features like Yarn
Workspaces,
which allows you to manage multiple packages within a single repository.
npm has also made improvements to its CLI and added useful features over time.
It's still widely used and familiar to many developers.

Security:

Both Yarn and npm have built-in security features to check for vulnerabilities
in the installed packages.
Both package managers regularly receive updates to improve security.

Community and Ecosystem:

npm has been around for a long time and has a larger user base. Consequently,
it has a more
extensive package registry with a broader range of packages available.
Yarn, being relatively newer, has a smaller community, but it's still
substantial and growing.

Integration with Build Tools:

Both Yarn and npm work well with various build tools and development workflows,
such as webpack, Babel, and others.

In summary, the choice between Yarn and npm largely depends on personal
preference
and the specific needs of your project. Both package managers are solid
choices,
and you can't go wrong with either. If you're already familiar with npm and
it meets your needs, there may not be a compelling reason to switch to Yarn.

Conversely, if you prefer Yarn's features or have specific reasons to use it,
it's a reliable option as well.

2023/07/21

Node.js:Does YARN allow us to find vulnerabilities ?

 Yarn does not have a built-in command to find vulnerabilities

in your project's dependencies directly. Unlike npm audit or Snyk,
Yarn doesn't provide an equivalent command to perform security
vulnerability scans.

However, you can use third-party tools like Snyk or retire.js
with Yarn to find vulnerabilities in your project's dependencies.
These tools work independently of the package manager and can be
used with Yarn projects as well.

Here's how you can use Snyk and retire.js with Yarn:

Using Snyk:

First, install Snyk globally on your system (if you haven't already)
by running the following command:

npm install -g snyk
Next, navigate to your Yarn project's root directory and authenticate Snyk
using:

snyk auth
Follow the authentication steps to log in or sign up for a Snyk account.

After authentication, run the following command to scan your Yarn project
for vulnerabilities:

snyk test
Snyk will analyze your project's dependencies and provide a list of
any known security vulnerabilities found.

Using retire.js:

First, install retire.js globally on your system
(if you haven't already) by running:

npm install -g retire
Next, navigate to your Yarn project's root directory
and run the following command to scan your project
for vulnerabilities:

retire
Retire.js will analyze your project's dependencies
and check them against its vulnerability database.

It's essential to remember that the security landscape
can change over time, and new tools or integrations might
become available. Always ensure that you are using the
latest versions of the tools and packages and follow best
practices for securing your Node.js projects. Additionally,
check the official documentation of Snyk and retire.js for
any updates or changes related to their usage with Yarn projects.

Node.js:Package Manger List

 


There are three main package managers for Node.js:

1) npm (Node Package Manager):
npm is the default and most widely used package manager for Node.js.
It comes bundled with Node.js installations, starting from version
0.6.3. npm allows developers to easily install, update, and manage
dependencies for Node.js projects. It has a massive registry containing
open-source packages that developers can use in their applications.

Example commands:

npm install <package>: Installs a package locally.
npm install -g <package>: Installs a package globally.
npm update <package>: Updates a package to its latest version.
npm uninstall <package>: Uninstalls a package.

2) Yarn:
Yarn is another popular package manager for Node.js,
developed by Facebook. It was created to address some
performance and security issues found in npm. Yarn uses a
different algorithm for dependency resolution and parallel downloads,
which can lead to faster and more reliable installations. Yarn is
compatible with the npm ecosystem and can use the same package.json
and node_modules structure.

Example commands:

yarn add <package>: Installs a package locally.
yarn global add <package>: Installs a package globally.
yarn upgrade <package>: Upgrades a package to its latest version.
yarn remove <package>: Uninstalls a package.

3) pnpm (Performant Node Package Manager):

pnpm is a newer package manager that aims to reduce disk space
usage and improve installation speed by using a global store for
dependencies and symbolic links. When multiple projects use the
same package and version, pnpm only stores one copy of that package
on the disk, reducing redundancy. It is compatible with npm and
Yarn and can use the same package.json and node_modules structure.

Example commands:

pnpm add <package>: Installs a package locally.
pnpm add -g <package>: Installs a package globally.
pnpm update <package>: Updates a package to its latest version.
pnpm remove <package>: Uninstalls a package.

It's worth noting that the Node.js ecosystem is continually
evolving, and new package managers or improvements to existing
ones might emerge in the future. For the most up-to-date
information, you can check the official websites and repositories
of npm, Yarn, and pnpm.

How to use snyk to find Vulnerabilities

 It seems like you are referring to "Snyk" (not "synk"),

which is a popular security tool that helps developers
find and fix vulnerabilities in their open-source dependencies.
Snyk can scan your project's dependencies and provide
detailed information about any known security vulnerabilities
found in the packages you are using.

To use Snyk to find vulnerabilities in your project,
follow these steps:

Install Snyk CLI:
If you haven't installed the Snyk Command Line
Interface (CLI) globally on your system, you
can do so using npm with the following command:

npm install -g snyk

Navigate to Project Directory:
Open your terminal or command prompt and navigate to
the root directory of your Node.js project.

Authenticate Snyk:
Before running the vulnerability scan, you'll
need to authenticate Snyk using the following command:

snyk auth
This will open a browser window where you can log in or
sign up for a Snyk account and authorize the CLI tool.

Scan for Vulnerabilities:
After authentication, run the following command to scan
your project for vulnerabilities:

snyk test
Snyk will analyze your project's dependencies and check them
against its vulnerability database. It will then display a
list of any vulnerabilities found, along with their severity
levels and suggested fixes.

Fix Vulnerabilities:
Snyk can often suggest ways to fix the vulnerabilities
automatically. You can use the following command to apply
those fixes:

snyk wizard
The wizard will walk you through the process of fixing
vulnerabilities by updating vulnerable packages to secure
versions.

Alternatively, you can also use the snyk monitor command to
continuously monitor your project for vulnerabilities and
receive alerts when new vulnerabilities are discovered in
your dependencies.

Remember to run snyk test periodically or integrate it into
your continuous integration (CI) pipeline to ensure that you
are regularly checking for vulnerabilities and keeping your
project secure. Keeping your dependencies up to date and
addressing vulnerabilities promptly is essential for
maintaining the security and stability of your Node.js project.

NPM audit fix --force

 The npm audit fix --force command is used to attempt to

automatically fix vulnerabilities in your Node.js
project's dependencies forcefully, even if the fix
results in breaking changes or may not be entirely
safe. This option should be used with caution, as
it can lead to unexpected issues and may introduce
compatibility problems in your project.

Using --force with npm audit fix can be considered
as a last resort when you encounter issues with
dependency updates, and you're willing to accept
the potential risks. Here are some things to consider
when using --force:

Breaking Changes: By forcing the fix, npm may update
packages to versions that have breaking changes, meaning
that your application might not work correctly with
the updated versions.

Compatibility Issues: The forced fix might update packages that
have inter-dependencies with other parts of your application,
leading to compatibility issues that could be hard to trace and resolve.

Manually Review Changes: Always perform a manual review of the changes
proposed
by npm audit fix --force. Carefully inspect the updates to understand the
potential impact on your project and the overall stability of the application.

Backup and Testing: Before using --force, it is essential to back up your
project,
including the package.json and package-lock.json files, to revert the changes
if something goes wrong. Additionally, conduct thorough testing after
the forced update to ensure that your application still functions as expected.

Use Specific Versions: Instead of using --force, consider manually
specifying exact versions for packages in your package.json file.
This allows you to have more control over dependency versions and
avoids unexpected updates.

It's generally recommended to avoid using --force unless you
have a good understanding of the potential consequences and
have exhausted all other options for resolving vulnerabilities.
Ideally, you should prioritize finding secure versions of the
affected packages and work on updating your application code
to be compatible with those versions.

If you choose to use npm audit fix --force, proceed with
caution and be prepared to handle any issues that may arise.
Keeping your application secure and functional is crucial,
and using forced updates should be a carefully considered decision.

How to find & fix vulnerabilities in node project

 Finding and fixing vulnerabilities in a Node.js project is

crucial for maintaining the security and stability of your
application. Here's a step-by-step guide on how to do it:

Audit Dependencies:
Start by auditing your project's dependencies. Node.js comes
with a built-in tool called npm audit that checks for known
vulnerabilities in the packages you are using. Run the
following command in your project directory:

npm audit
This will give you a summary of any vulnerabilities found,
along with their severity levels and suggested fixes.

Update Dependencies:
Once you have the audit results, update your dependencies to their
latest secure versions. Often, vulnerability fixes are released in
newer versions of packages. You can use the following command to
update your packages:

npm update
Note that updating packages might introduce breaking changes,
so it's essential to test your application thoroughly after the update.

Use a Security Scanner:
Consider using a third-party security scanner or vulnerability
assessment tool specific to Node.js. These tools can perform
in-depth analysis and provide additional insights into potential
security issues. Some popular security scanners for Node.js projects
include:

nsp (Node Security Platform) - Now part of npm audit since npm v6.0.0.
snyk - Provides detailed vulnerability information and integrates
well with npm projects.

npm audit - Built-in to npm, it's always a good starting point.


Follow Security Best Practices:
Ensure that you and your team are following security best
practices when developing the application. This includes using safe
coding practices, securely handling user input, employing proper
authentication and authorization mechanisms, and validating third-party
input and data.

Monitor for New Vulnerabilities:
Regularly monitor for new vulnerabilities in your project's
dependencies. Security issues can be discovered in packages
after you have installed them. By staying up-to-date with
vulnerability databases and security announcements,
you can proactively address potential threats.

Use Security Headers:
Configure your application to use security headers to
protect against common web vulnerabilities like
Cross-Site Scripting (XSS), Cross-Site Request Forgery
(CSRF), etc. Use frameworks like helmet to easily implement
these headers.

Secure Environment Configuration:
Ensure that sensitive information like passwords,
API keys, and database credentials are not hard-coded
in your codebase. Use environment variables to manage
such sensitive data securely.

Security Testing:
Implement automated security testing, such as
penetration testing and security code reviews,
to detect potential vulnerabilities before
they become a problem in production.

Regularly Review Codebase:
Conduct regular code reviews with a focus on security.
This helps identify potential vulnerabilities and
ensures that security practices are followed consistently.

Stay Informed:
Stay up-to-date with security news, community discussions,
and relevant best practices. Being aware of emerging
security threats and solutions will help you proactively
address potential issues.

Remember that security is an ongoing process, and it's
essential to be vigilant in keeping your Node.js project
and its dependencies secure. Regularly check for
vulnerabilities, update your packages, and adopt secure
coding practices to minimize the risk of security breaches.

NPM Audit fix

 npm audit fix is a command used to automatically fix vulnerabilities

found in your Node.js project's dependencies. It is provided by npm,
the Node Package Manager, and is a useful tool to ensure your project
is using secure packages.

When you run npm audit fix, the following steps are typically taken:

Audit: The command first runs npm audit to identify any known security
vulnerabilities in the packages you have installed in your project.

Resolve Vulnerabilities: It attempts to automatically resolve the
vulnerabilities
by updating the affected packages to their latest secure versions.
If possible, it will update to a version that does not have the vulnerability.

Package.json Update: If npm audit fix makes any changes to the
installed packages, it will update the package.json file to
reflect the new package versions and their dependencies.

Lock File Update: It will also update the package-lock.json file
(or npm-shrinkwrap.json for older versions of npm) to ensure that
the dependency versions are locked in, providing a consistent
environment for future installations.

Dependency Tree Restructuring: In some cases, resolving vulnerabilities
might result in changes to the project's dependency tree, including the
installation or removal of certain packages to satisfy version requirements.

It's important to note that while npm audit fix is a handy tool for
automatically fixing vulnerabilities, it may not be able to resolve
all issues. In some cases, you might need to manually update dependencies
or address vulnerabilities by changing the way you use certain packages in
your code.

Keep in mind the following best practices:

Always review the changes proposed by npm audit fix before accepting them,
as updating dependencies could introduce breaking changes to your project.

Make sure to test your application thoroughly after running npm audit fix
to ensure that the updates did not introduce any regressions or compatibility
issues.

Regularly audit your project for vulnerabilities and update dependencies as
new security patches are released. This is an ongoing process to maintain a
secure application.

To run npm audit fix, open your terminal and navigate to your Node.js
project's directory, then run the following command:

npm audit fix

After the command completes its tasks, remember to check the project for any
unintended consequences and verify that your application still functions correctly.