All posts by admin

Debug typescript in Node JS

demo download

Create REST API with Typescript


mkdir Und-TSC-sec15
cd Und-TSC-sec15

Create Node Project
npm init
You’ll then have a package.json file.


You’ll then have a tsconfig.json file.

In tsconfig.json:

Now let’s install the needed modules:

standard web server independencies:
npm install –save express body-parser

development independencies:
npm install –save-dev nodemon

create src folder:
mkdir src
cd src
touch app.ts

When you are done, type tsc to compile the typescript into javascript.

Then you can debug it. Put a breakpoint there and make sure you’re on the index file. In our file, we’re on app.ts.

Once you’re on that file, go to Run > Start Debugging. You’ll see the bottom status bar turn orange. This means the server is running.

Click on View > Terminal, and you’ll see the terminal pop up. Then click on debug console. You’ll be able to see the console log from the node js app appear.

Creating Routes


cd src/routes
touch todos.ts

We extract Router from express. We can then register routes to hit functionality.
We set up the router to receive POST, GET, PATCH, and DELETE on ‘/’.
Each HTTP request will get mapped to certain functionalities that we declare in controllers/todos file.

routes/todos.ts

Finally, we need to connect our router to our server for endpoint /todos.

app.ts

Add additional routes

First, we create a class Todos so we have a structure to work with. We export a class Todo so other modules can import it, and then new it to create an instance of Todo.

Then import the class so that we get a simple data structure going.

We create functionality by implementing a function createTodo.
Note that we use RequestHandler interface, which contracts us to use
req, res, and next parameters.

controllers/todo.ts

Since it takes care of a POST request, we use parse the body property in the request
object to get the body data. The body data’s key is text.

In order do that we need to import the body-parser package in app.ts, and then extract json.
This is so that we parse the body using json.

app.ts

Open up your postman and query it like so:

class – typescript to js

ref – https://www.geeksforgeeks.org/typescript-class/

typescript

gets converted to js:

What does ‘this’ reference inside a function in an IIFE?

We have functions in IIFE, and we see that it uses this. But what does this reference?
As you can see from the example below, the ‘this’ keyword refers to the IIFE object.

> test4.bye()

“bye bye”

> test4.hello()

hello reference sayHello function. sayHello logs the ‘this’ keyword of the IIFE.
It will display the IIFE object.


Object
bye: ƒ sayBye()
hello: ƒ sayHello()
__proto__: Object
“hallo!!!ricky”

However, notice that we return a literal object. We can’t use new on the literal object because it’s not a function. So we must change this a bit in order to accomodate ‘new’.

So in our IIFE Student, we have a function constructor Student. That way when we go new Student, it would be valid because we can instantiate a function instructor.

Accessing Attributes and Functions

A class’s attributes and functions can be accessed by the object. With the help of ‘ . ’ dot notation or bracket notation([”]) we access the data members of a class.

child processes in Node JS 2

getCount.js

index.js

tasker.js

queue.js

child process in Node JS

ref – https://www.digitalocean.com/community/tutorials/how-to-launch-child-processes-in-node-js

Creating a Child Process with fork()

index.js

Fork is a variation of spawn. To create a process that’s also a Node Process.

Main benefit of fork over (exec, spawn) is that fork enables communication between the parent and child process.

CPU intensive tasks (iterating over large loops, parsing large JSON) stop other JS code from running. If a web server is blocked, it cannot process any new incoming requests until the blocking code has completed its execution.

1) Now run the server
2) run /hello (1st time)
3) run /total
4) run /hello (2nd time)

So we’ll only see the result from the first /hello. The slow function will block other code, and that’s why we won’t see the 2nd /hello.

The blocking code is slowFunction.

So how do we solve this?

Move blocking code to own module:

getCount.js

Since it will be run with fork, we can add code to communicate with the parent process when slowFunction has completed processing. Let’s send a message to the parent process with JSON message.

– Why look for message ‘START’? Our server code will send the START event when someone access the ‘/total’ endpoint.
– Upon receiving that event, we run slowFunction().
– we use process.send() to send a message to the parent process.

index.js

getCount.js

Run the app: node index.js

Open a 2nd terminal and type: curl http://localhost:8000/total
This will start up a long running task at say 7:41:18.

Open a 3rd terminal and type: curl http://localhost:8000/hello

Hi it a bunch of times. As you can see, it is running concurrently and not blocking the main JS code. This is because its a child process that’s running it concurrently. From the time stamp, you will also see that it’s happening after 7:41:18.

Then when the long task is done, it stops at 7:42:20. This proves that the /hello logs before 7:42:20 were all done concurrently with the task at /total.

Worker Thread with Node JS

mkdir spawnEx
then ls into that directory

set it up all default
npm init

create an index.js file
touch index.js

Open it up with VCode
Code . index.js

copy and paste the code like so:
index.js

Then we create the run file. use worker_threads to extract Worker object. We create a new worker whenever we call runService().

run.js

Create a worker class.
touch worker.js

worker.js

test.txt

I will show the time at milliseconds of when the worker has written to the text.txt file. As you scroll down using the right hand scroll bar, you’ll notice this millisecond increase. This is the increase of time, and you’ll see exactly which worker was executing at that time.

When you should use Node JS

ref – https://livecodestream.dev/post/when-you-should-and-should-not-use-nodejs-for-your-project/

A multi-threaded program has a pool of threads that run concurrently to accept requests. The number of threads used by the program is limited by the system’s RAM or other parameters. So, the number of requests it can process at a given time is limited to this number of threads.

Whereas the single-threaded Node.js program can process any number of requests at a given time that are in the event queue to be executed. Node’s event loop uses a single-threaded implementation when handling events. Each event is handled one after another in the order they arrive by a single processor thread. The requests received to a Node web server are served in the order they were received.

However, there is a downside to Node.js being single-threaded. The single-threaded implementation makes Node a bad choice for CPU-intensive programs. When a time-consuming task is running in the program it blocks the event loop from moving forward for a longer period. Unlike in a multi-threaded program, where one thread can be doing the CPU-intensive task and others can handle arriving requests, a Node.js program has to wait until the computation completes to handle incoming requests.

Node.js introduced a workaround for this problem in version 10.5.0: worker threads. You can read up more on this topic to understand how to use worker threads to solve this problem for CPU-intensive programs.

You may now have a question? How can a single thread handle more events at a given time than a thread pool if events are handled one after another and not concurrently? This is where Node’s asynchronous model steps in. Even though the Node’s event loop implementation is single-threaded, it achieves a concurrent-like behavior with the use of callbacks.

Assume you want to connect to a separate API from your Node server to retrieve some data.

You send a request to this particular API from the server. You also pass a callback function with the instruction on what to do when the response from the API is received.

After executing the task that makes the request to the API, the Node program doesn’t wait for the response from the that API. Instead, after sending the request, it continues to the next step of the program. When the response from the API arrives the callback function starts running, and therefore handles the received data. In this manner, the callback function runs concurrently to the main program thread.

In contrast, in a synchronous multi-threaded program, the thread sending making the API call waits for the response to arrive to continue to the next step. This does not stall the multi-threaded program because, even though this one thread is waiting, other threads in the thread pool are ready to accept receiving requests.

The asynchronous feature is what makes the single-thread of the Node.js program quite efficient. It makes the program fast and scalable without using as many resources as a multi-threaded application.

Naturally, this makes Node a good fit for data-intensive and I/O intensive programs. Data-intensive programs are focus on retrieving and storing data, while I/O-intensive programs focus on interacting with external resources.

When to Use Node.js?

Now back to our main question. When should you use Node.js for your projects? Considering the main features of Node.js and its strengths, we can say

– data-driven
– I/O-driven
– event-driven
– non-blocking

applications benefit the best from a Node.js implementation.

Especially, web backends that follow microservices architecture, which is now growing in popularity, are well suited for a Node implementation. With the microservices architecture, sending requests from one microservice to another becomes inevitable. With Node’s asynchronous programming, waiting for responses from outside resources can be done without blocking the program thread.

Unlike a multi-threaded program, which can run out of threads to serve incoming requests because many threads are waiting for responses from external resources, this I/O-intensive architecture does not affect the performance of the Node application. However, web servers that implement computational-heavy or processes-heavy tasks are not a good fit for Node.js. The programming community is still apprehensive of using Node with a relational database given Node tools for relational databases are still not as developed as compared to other languages.

Heavy Computational Applications

If your application is likely to run tasks that involve heavy computing and number crunching, like running the Fibonacci algorithm, Node.js is not the best language to turn to. As discussed above, the heavy computation blocks the single-thread running in the application and halts the progress of the event loop until the computation is finished. And it delays serving the requests still in the queue, which may not take as much time.

If your application has a few heavy computational tasks, but in general benefits from Node’s characteristics, the best solution is to implement those heavy computational tasks as background processes in another appropriate language. Using microservices architecture and separating heavy computational tasks from Node implementation is the best solution.

process.nextTick() vs setImmediate()

ref – https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

process.nextTick() vs setImmediate()
We have two calls that are similar as far as users are concerned, but their names are confusing.

process.nextTick() fires immediately on the same phase

setImmediate() fires on the following iteration or ‘tick’ of the event loop

In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change. Making this switch would break a large percentage of the packages on npm. Every day more new modules are being added, which means every day we wait, more potential breakages occur. While they are confusing, the names themselves won’t change.

We recommend developers use setImmediate() in all cases because it’s easier to reason about.

Unpacking fields from objects passed as a function parameter

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

mongo db commands

ref – https://www.tutorialspoint.com/mongodb/mongodb_create_database.htm

MongoDB’s

use some DB name is used to create database. The command will create a new database if it doesn’t exist, otherwise it will return the existing database.

However, you must have at least 1 document in your DB before it shows up in the list. So we create one collection and insert 1 document in order for the DB to exist.

WriteResult({ “nInserted” : 1 })

show dbs

and you’ll see database portfolio listed.

Kafka Node

https://www.npmjs.com/package/kafka-node
kafka-node-hello-world

We first require kafkajs module and extract the class. We then create a topic and group ID.
It is simply to identify the group that will be consuming, and the name of a topic that we’ll be producing.

Then we instantiate it with a unique client id. For brokers let’s use localhost:9092 because that is what we’re using in our Kafka settings file.

get a producer

get a consumer

Consumers Subscribe

Consumer Run

Consumer Unsubscribe

Producer Start

Producer Send Data

Producer Stop