Separating socket.io namespaces into separate files - node.js

I've written two relatively large socket.io apps, one for playing a game and the other for chat, which I've separated into two namespaces.
I would like to now move these out of my main file app.js into some namespace directory, and just require them in my express app leaving all of the functionality intack.
How would I go about this, or is there some way to get the effects of what I'm looking to do in some other manner?

In order to use separate files you need to use modules in node.js and use require to load them.
Modules have special structure and syntax to follow, in order to be able to call modules functions and interact with it.
Read about modules here: http://nodejs.org/docs/latest/api/modules.html
If you need to interact with functions, objects and data inside of the module, then it might be a lot of work on remaking architecture of your application.
This is something that you have to take care from the earliest moments of the development, in the process of architecture and technical design of application.
To use same socket, you have to initialize it in parent module that require child modules, and pass socket app handle to those child nodes, that they will be able to use it.
The worst and straight forward option to make it, and is absolutely not the option in commercial world, is to load js file content and just eval() it. But remember - this is absolutely not recommended and in commercial world you should never use it.

Related

How to create shared language resources with i18next in multi-app node/express & react monorepo?

I just started to use i18next in my monorepo (new to it), which has several serverside microservices and a couple of frontends, including several custom library components. Many of the language strings are shared, and some are app specific. I could not decide on a logical way to approach the problem.
Tooling: Typescript - Node/Express - React/Vite - Electron/React (Desktop)
Firstly, questions:
Where should I keep the language resources during development? In another library? App in monorepo? Under each library module?
From where should I serve them? Something like lang.mydomain.com? Re-dividing them under each app during build (e.g. with Vite)?
All examples/tutorials I could reach use a single app and use i18next.js/ts to be included at the app level. I think I need to wrap it into a library module for my purposes. How can I do that, without losing access to its capabilities/types/methods etc? Dynamically creating instances in a higher-order module (the library is extensive, and I'm nearly lost)?
My initial thoughts:
As many translations will be shared, translating each one will be illogical, they should be shared.
As there can be many languages, it seems using i18next-http-backend is logical for web and embed with i18next-fs-backend for desktop app.
Dividing the resources as common/graphs/tables/ui etc will be logical (these will be divided in a library module hierarchy though).
A logical way can be to include a module's language resources in the module but that would not help translators, they should be at the same place at the top level in this respect.
PS: I used to use react-intl-universal, it is really easy, but it's release schedule is falling back.
Thank you in advance...

Advantages of using #Module NestJS

I'm making a new NestJS app and after a lot of errors on the first because the multiple modules I created didn't have the correct imports, providers, exports, TypeOrmModule.forFeature etc made me wonder: What was the point?
Why not use only the app.module and just dump everything in it? All the controllers and services and entity types and any other that may come up?
From the documentation:
We want to emphasize that modules are strongly recommended as an
effective way to organize your components
Is that the only reason? Organization?
Does dependency injection play a role of some kind?
Edit:
If organization is the main reason, why not separate in a different folder with a controller and service? Basically a module without the imports, providers etc. Doing the same thing with less boilerplate.
Why not use only the app.module and just dump everything in it?
Better yet, why use multiple files at all? Why not just have a couple thousand line index.js with no types, no organization, just raw JS all the way down?
The answer? Code organization and ease of re-use. By making these modules, you should be grouping together similar logic together. All the code for a single feature should be available by just importing FeatureModule and usable. When it comes to library modules, this becomes pretty apparent: TypeOrmModule has a forRoot/forRootAsync and a forFeature which exposes ways to inject repositories into your services. The JwtModule has a register/registerAsync and exposes a JwtService so you can configure the JwtService once and re-use the provider.
When dealing with entity features this may look messier, but technically it's all still possible, so that in theory you'd be able to take FeatureModule from Application A and drop it into Application B and have everything still working with regards to the FeatureModule, similar to how pulumi has the idea of stacks and applications and you can just spin up new applications using the same group of components.
The module system, once you get the hang of it, and in my opinion, makes it very easy to recognize what all a module will be working with, with regards to other features and how they're connected. It's just a matter of discipline and learning the feature of the framework.

Express route handler like functionality in Sails applications

TL;DR Is there a way to have Sails applications work similar to Express route handlers?
I'm working on an application that has a few major components (e.g. ecommerce, blogging and so on). It's working all fine, but the huge number of models, controllers and views is making it difficult for me to visualize them as separate components and making me feel a little too congested for comfort.
I've been through threads like this and I understand nesting is available for controllers, but I really want to split my project into discrete components.
What I'm doing now is splitting the project into different applications and exposing their REST APIs for the gluing application to show its magic. At least this would do the much-needed segregation. But how do I make the endpoints accessible to the gluing application? Using req? While that would give me the liberty to host the other components on another machine, it would slow things down considerably, right? Is there a way to interact with the other processes "directly", something like route handlers in Express (though they're not separate processes)? I would ideally like to have them running as separate processes so one component doesn't bring everything down on failure. At the same time, I want the interaction to be as "local" as possible.
Am I missing something fundamental here? Any suggestions would be appreciated.
Also, is this more of a serverfault question?

General terminology put into context

I learned Java programming before learning any other programming languages. As I learn Node.js, I'm getting all the terminology confused. I have always thought API as a library of methods, classes, etc. that someone has built to make our lives easier. Then I learned about module, which I basically assume to be the same thing as an API(list of methods already built by someone). THEN, I learned about the Express Framework, which again, is a list of methods just like a module and an API. Moreover, the way we incorporate these features into our program is all by doing something like
Var http = require('http');
Therefore, can someone who understands the distinctions between these terms put these terms in context(examples) that could address my question.
Thanks a lot for the help.
A library is just a collection of numerous modules, classes, functions, etc. that are related to each other.
A framework is either a type of or a part of a library that is setup for you to build on top of rather than just call upon. And the distinction between Library and Framework can sometimes be a bit blurred.
With Express, you build upon the Application and its Router which handles incoming requests and determines when to call your code.
app.get('/', function (req, res) {
// ...
});
Though, frameworks can also span beyond code into tools. compound.js' executable is a good example of this.
A module is an individual piece of a library or framework. With Node, it's a single script file and the Object that is exported from the script.
An API is the summary/description of how you interact with the library, framework, or module.
It's usually what you'll find in documentation and is the accessible members, their name, their type, what arguments they accept, etc.
Express' API is:
express
Type: function
Named Arguments: (none)
Returns: Application
Members
listen
Type: function
Named Arguments:
name: port
Type: Number
etc.
This is largely an opinionated question. But I will attempt to provide the some terms commonly used by the Node community, and roughly the factual differences between them.
Module as it pertains to Node is very similar to what you would associate with a Java Library. It provides a wrapper around things that Node users find they do a lot. Frequently providing wrappers around node library functions for doing things everyone wants to do. A simple example would be a recursive file system reader, like wrench. Modules also extend to files you use to modularize your code. For example, modules aren't only installed via NPM, but separate javascript files you write as part of your code base to separate code functionality, under standard OOP practices.
require('someNPMINStalledModule')
require('./someFileInYourCodeBase.js')
both are modules. One is installed via NPM and located in node_modules directory, in the directory you launched node from. The latter example is a javascript file located in the directory you launched node from.
Then there are frameworks. At the core these do the same thing as modules, however, they are meant to be more wide spread, and really change the way you use node. In the java world frameworks like Express would be similar to things like Grails. You can still include and do everything you can do in Java, but grails wraps some things for you, and provides convenient powerful method calls for doing batches of work in a less verbose way. In the end you end up with functionally equivalent code, but Grails has allowed you to accomplish more in fewer lines of code, by generalizing the language a little more. But it still, as I said, allows you to use native code, when Grails doesn't provide the functionality you need. At the cost of this 'few lines of code' gain, you have added a layer of abstraction, additional function calls, etc. This distinction is unimportant, unless you are one who cares deeply about style. A hardcore ExpressJS developer likely wouldn't like it if you included a plain node http server in your code. Not so much because it is invalid Node, or from a perforamnce view any different, it wrecks the style of your code. If your code uses a framework, you should stick to using the coding conventions as used in this framework. But if you use a module like wrench to recursively search a directory, it is still perfectly stylistically acceptable to use fs.readFile, to read a single file.
Then there are mini applications which is a module that allow you to quickly launch simple things like serving a file. For example: http-server will server a directory of files to any port you wish, with a simple command line. You wouldn't use them in your own code with 'require' but this type of module can honestly be some of the most useful thing node provides, I highly recommend using some. (Nodemon, http-server, and grunt are a few highly useful examples of modules that can help make your development life easier)
Finally there are Native Extensions. The concurrency that Node provides comes from the V8 backend. Replicating this in pure Javscript is impossible, and the only way to write truly asyncrhonous code is to take advantage of asynchronous operations provided by the Node API, do some really wonky logic with process.nextTick, fork child processes, or write native extensions. Native Extensions provide truly concurrent operations that Node does not provide. Database communication is the most obvious example, but anyone can develope a C++ extension that will spawn threads to do work. There is also a very handy module that launches threads to handle bits of Javascript called "threads a gogo". It simplifies the launching of truly concurrent work, though if you're in a position where such things are necessary, you may find that you're using the wrong language for your use case. Ultimately these are no different from Modules in the way that you use them, but being aware of the fact that they can provide additional concurrent method for I/O type of operations not provided by NodeJS APIs is a unique and very important distinction.

How to use `domain` module properly in Node.js

What is the proper way of using domain module in NodeJS applications?
Wrap up the code blocks with the domain instance like how we use try-catch blocks? If yes, should we create new instances of domain each time for each separated block?
Wrap up the main function with the domain run method? If yes, is that really sufficient for an enterprise application for example?
P.S. Is there any well-known open-source node project with an extensive use of domain module where I can study their code?
P.P.S. Looking at the node documentation and tutorials, I see that almost all of them just simply wrapped up the main function within the domain's run method, however as far as I can see they are mostly copying each other. I basically can't see how people use domain module in different situations (what I see is mostly a copy of node documentation with couple of minor changes)

Resources