Node.js 开发模式(设计模式)

简介: Asynchronous code & Synchronous code As we have seen in an earlier post (here), how node does things Asynchronously.

Asynchronous code & Synchronous code

As we have seen in an earlier post (here), how node does things Asynchronously. For a “Traditional programmer”, this can be a tough pill to swallow. So lets take a look at how things can be done async.

Tradition programming

Here the  doSomething() executes a set of statements that are not dependent on the response of the db call. But it has to wait till the db operation is completed. This is why we have a server like Node to take care of all the I/O threads separately.

So in an async world, the same will be written like this

Here, the DB request gets fired and doSomething()  will get executed immediately after that. All the actions happen async. Its Node’s event loop’s responsibility to take care of I/O operations and fire the registered callback.

Now, life is always not that simple is it? (tell me about it!..) Take a look at this example

or

Very nested and convoluted? So can we fix this whole nested thing? Yes, you can use any of the following modules

So our code will turn into

Now, lets take a look at Node’s Modules.

Node Modules

If you have interacted with programming languages like C, C++, Java, .Net or PHP, you would have seen statements like import  using  #include  include or  require to get external files/libraries to your current file. Since the code is isolated in these programming languages, we need to explicitly include the required libraries.

But, Javascript runs everything in the global scope and does not have a partition between variables/functions or variables/functions of a file. In simple, there is no namespacing!.

If you have 3 files, fileOne.js , fileTwo.js  & fileThree.js  and you loaded them in your browser in the same order, The function definition or variable values of the prior will be overridden by the later without any warnings.

Lets say fileOne has a method called add(num1,num2);  which adds two numbers & fileTwo has a method called add(str1, str2);  which concats’ two strings. And fileThree is calling theadd(5,4);  expecting the method to return the sum. But instead, it receives a concatenated string.

This phenomenon in the programming world is called as the “spaghetti code”. Unless you are careful about your variables names, you might override someone else’s code or some one might override yours!

So we need to use a dependency management system, that will take care of things like these. Node uses CommonJs Modules for handling dependency.

CommonJS dependency management revolves around two methods exports  &  require.

Let’s reconsider the above example, and implement the same via CommonJs modules.

fileOne.js

fileTwo.js

and now in fileThree.js

Neat right? Node uses this for its dependency management & name-spacing and you need to when you are developing code around Node.

Javascript’s Callback

A call back basically is a function that will get invoked after the initiated task is completed.

That means, I want do something after some other thing is completed. Like, after 5 seconds fire an alert.

Or in Node, since everything is async, the callback gets fired on completion of an I/O operation.

Callback function can be named or anonymous.

As we have seen earlier, nesting callbacks can be a nightmare for code readability. We have also seen libraries like async would help clean the code for us. Another way to implement the same without any external module is

Any async function in node accepts a callback as it’s last parameter.

So, this is what you can expect from Node.

And the callback function’s first argument is always an error object (if there an error, else null) and the second argument is the results from the parent Function.

The Event Emitter Pattern

Let’s take a look at some sample code first

The above code is a simple TCP server. Lines 4,7 & 10 register events. And the server gets created. When a client navigates to  http://localhost:1235 the server starts to listen to the new client. And registers events when a data comes in & when a client disconnects from the server.

So when a client connects, we see a console log about the connection. We wait.. wait.. wait.. and then the client emits a data event, the server logs it & finally the client disconnects.

This model is also called as the “PubSub” - A publisher-subscriber. For all you jQuery devs out there, you know this!! (You register an event on a button click and write some code and wait for the button click). Some call this as Observable pattern. You can figure this out here.

So, In simple, our server code will get executed only if there is an action.This is a simple example of event driven development in Node.

Node provides an option to write & trigger custom event too. Take an example of a baseball

What happened here?

  • We created a response ( homeRun())
  • We registered an event (‘ swing’) passing the callback ( homeRun())
  • We Emitted the event (‘ swing’)

Apart from the above way of implementing the eventEmitter, we can inherit the same too. What do I mean? Take a look at this

Pretty neat right? Now you can have your own class that is invisible.

So these are some of the ways, in which node should be implemented. Depending on our requirement, you can pick from above.

相关文章
|
13天前
|
设计模式 前端开发 JavaScript
【JavaScript 技术专栏】JavaScript 设计模式与实战应用
【4月更文挑战第30天】本文探讨JavaScript设计模式在提升开发效率和代码质量中的关键作用。涵盖单例、工厂、观察者、装饰器和策略模式,并通过实例阐述其在全局状态管理、复杂对象创建、实时数据更新、功能扩展和算法切换的应用。理解并运用这些模式能帮助开发者应对复杂项目,提升前端开发能力。
|
5月前
|
设计模式 JavaScript 数据安全/隐私保护
js设计模式之工厂模式
js设计模式之工厂模式
35 0
|
4月前
|
设计模式 前端开发 算法
【面试题】 ES6 类聊 JavaScript 设计模式之行为型模式(二)
【面试题】 ES6 类聊 JavaScript 设计模式之行为型模式(二)
|
1天前
|
设计模式 JavaScript 前端开发
js设计模式-观察者模式与发布/订阅模式
观察者模式和发布/订阅模式是JavaScript中的两种设计模式,用于处理对象间的通信和事件处理。观察者模式中,一个主题对象状态改变会通知所有观察者。实现包括定义主题和观察者对象,以及在主题中添加、删除和通知观察者的功能。发布/订阅模式则引入事件管理器,允许发布者发布事件,订阅者通过订阅接收通知。
|
1天前
|
设计模式 JavaScript 算法
js设计模式-策略模式与代理模式的应用
策略模式和代理模式是JavaScript常用设计模式。策略模式通过封装一系列算法,使它们可互换,让算法独立于客户端,提供灵活的选择。例如,定义不同计算策略并用Context类执行。代理模式则为对象提供代理以控制访问,常用于延迟加载或权限控制。如创建RealSubject和Proxy类,Proxy在调用RealSubject方法前可执行额外操作。这两种模式在复杂业务逻辑中发挥重要作用,根据需求选择合适模式解决问题。
|
2月前
|
设计模式 缓存 JavaScript
js常用设计模式
js常用设计模式
25 1
|
5月前
|
设计模式 存储 JavaScript
js设计模式之单例模式
js设计模式之单例模式
49 7
|
10月前
|
设计模式 前端开发 JavaScript
|
7月前
|
设计模式 JSON 前端开发
前端面试必看(手写Promise+js设计模式+继承+函数柯里化等)JavaScript面试全通关(1/3)
前端面试必看(手写Promise+js设计模式+继承+函数柯里化等)JavaScript面试全通关(1/3)
43 0
|
8月前
|
设计模式
js-设计模式
设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。