Node.js app structure, "folder by features" routing - node.js

I'm making a scalable REST-API, but I barely find articles on advanced node.js application structures in terms of a big application, since most of them are using simple starter projects.
I'm using the "folder-by-feature" structure, based on this article and this answer.
My question: what is the better structure of the solutions bellow?
1. Keep the routes in a separate folder:
src
product
index.js
product.spec.js
routes
index.js
product.js
user.js
user
index.js
user.spec.js
2. Put the route into its corresponding folder:
src
product
index.js
product.route.js
product.spec.js
user
index.js
user.route.js
user.spec.js
Using the routes in the index.js files.
Are there any better solutions?
Any article about advanced, scalable node project structures would be appreciated!

Since this is an opinion question here is mine:
My build migrates everything from src to dist. Some is compiled and some is just copied. I then run directly from the dist folder.
src
api
<api files/folders>
lib
<common lib files/folders>
routes
<Route files (app.use, app.get, etc.)>
static
<static css, images, script, etc.>
<I do not include src code that is compiled in any way>
ui
<LESS, SASS, JS, etc that will be compiled, combined, packed, etc>
views
<ejs files>
app.js
Things in src/ui/** get compiled and placed into dist/static/**.

Related

How do you name test files with unit tests in NodeJS project?

I have a NodeJS backend app using express framework.
I want to put my tests into a dedicated folder, say test in the root of the project.
And inside that folder I am going to have two sub-folders: unit for unit tests and integration for endpoint tests.
My question is what is the common practice around naming the unit-test files when they are not co-located with the source code file that they test?
I am considering to simply reflect the file path in the test-file name by joining the path with dots, e.g. controller.products.test.js for a products.js controller code that lives under the controller folder.
But is there any common way/convention that people of NodeJS normally follow?
Here is the structure:
/
/models
/controllers/
product.js
category.js
/middleware/
auth.js
validation.js
/test/
/unit/
controllers.product.test.js
middleware.auth.test.js
/integration/
products.test.js
index.js
package.json

NestJs Microservice - Which location do I read files from?

Wondering if anyone can help? I am trying to learn how to use NestJS microservices. I have managed to succesfully get a microservice with MQTT transport setup to receive events from an API. I am trying to use pug to merge the event information with a html template file. However pug cannot find the template file...
this.logger.info(`Running from dir ${__dirname}`); // /usr/src/app/dist/apps/microservice
const template = pug.compileFile('../templates/email.pug');
I have used a logger to display __dirname which refers to the dist directory. This has the single file main.js inside. How do I bundle and read a template pug file from nestjs microservice?
This post has a similar question, however it is for a nestjs app.
First we need to configure the express instance
// main.ts
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.setViewEngine('hbs');
Put templates folder in root with the neighborhood src folder
but you must find it not in dist folder because Typescript compiler dont copy non-typescript files to dist folder for that approach you can use copy-webpack-plugin
but i just advise you change this url( ../templates/email.pug) so that to find folder located in root not find it in dist
hope it will help you! if not please provide your file structure.
https://docs.nestjs.com/techniques/mvc

What is index.js used for in node.js projects?

Other than a nice way to require all files in a directory (node.js require all files in a folder?), what is index.js used for mainly?
When you pass a folder to Node's require(), it will check for a package.json for an endpoint. If that isn't defined, it checks for index.js, and finally index.node (a c++ extension format). So the index.js is most likely the entry point for requiring a module.
See the official Docs here: http://nodejs.org/api/modules.html#modules_folders_as_modules.
Also, you ask how to require all the files in a directory. Usually, you require a directory with an index.js that exposes some encapsulated interface to those files; the way to do this will be different for ever module. But suppose you wanted to include a folder's contents when you include the folder (note, this is not a best practice and comes up less often than you would think). Then, you could use an index.js that loads all the files in the directory synchronously (setting exports asynchronously is usually asking for terrible bugs) and attaches them to module.exports like so:
var path = require('path'),
dir = require('fs').readdirSync(__dirname + path.sep);
dir.forEach(function(filename){
if(path.extname(filename) === '.js' && filename !== 'index.js'){
var exportAsName = path.basename(filename);
module.exports[exportAsName] = require( path.join( __dirname, filename) );
}
});
I hardly ever see people wanting to use that pattern though - most of the time you want your index.js to go something like
var part1 = require('./something-in-the-directory'),
part2 = require('./something-else');
....
module.exports = myCoolInterfaceThatUsesPart1AndPart2UnderTheHood;
Typically in other languages the web server looks for certain files to load first when visiting a directory like / in priority, traditionally this is either: index or default. In php it would be index.php or just plain HTML it would be index.html
In Node.js, Node itself is the web server so you don't need to name anything index.js but it's easier for people to understand which file to run first.
index.js typically handles your app startup, routing and other functions of your application and does require other modules to add functionality. If you're running a website or web app it would also handle become a basic HTTP web server replacing the role of something more traditional like Apache.
Here is a good article explaining how Node.js looks for required module https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8, with folder and index.js file
Modules don’t have to be files. We can also create a find-me folder
under node_modules and place an index.js file in there. The same
require('find-me') line will use that folder’s index.js file:
~/learn-node $ mkdir -p node_modules/find-me
~/learn-node $ echo "console.log('Found again.');" > node_modules/find-me/index.js
~/learn-node $ node
> require('find-me');
Found again.
{}
>
Late to the party but the answer is simply to allow a developer to specify the public api of the folder!
When you have a bunch of JavaScript files in a folder, only a small subset of the functions and values exported from these files should exportable outside of the folder. These carefully selected functions are the public apis of the folder and should be explicitly exported (or re-exported) from the index.js file. Thus, it serves an architectural purpose.

Getting started with Chaplin and node.js

Is there a way to use Chaplin with node.js/express? I haven't found a single tutorial or an example on this subject.
If so, how do I get started? How would the folder structure look like? Or my server.js file?
Chaplin appears to be purely client side. For a basic app your back end could be a static HTML page. It requires no particular server structure.
Backbone, which it's built on, expects a RESTful JSON API to persist its models, but otherwise doesn't require a backend either. If your app has models which need to be saved (likely), then you'll want to look into tutorials for writing a REST API in express (there are many) or for extending Backbone to suit your particular backend needs.
So to get started, your server.js file will look exactly like the one created by the express install script.
There's no de facto best practice for how to structure the folders in an end-to-end javascript app. In my experience I tend to keep client side javascript in its own folder (/client, /app/client, /lib/client, etc), then generate the publicly exposed compressed/concated scripts in a build step. To get started, you might just deposit them in /public/javascripts.
I still don't understand this..
In my express file it says
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
Should I move all my chaplin app files into that views folders or how do I launch them?
Anyway, express seems to use this jade thing but chaplin does not, how does that go?
My problem is to understand where everything goes and why.
Express creates it's own folder structure:
node_modules
public
routes
views
app.js
then again chaplin has it like this:
app
generators
bower.json
config.json
etc.
in that app folder:
assets
controllers
lib
models
views
Now, where do I place all of this chaplin stuff in my node folders? under public or views or where?
And then how do I get this whole thing started? Do I just include all the chaplin .js files in that index file I have in my node.js views folder (jade file)?

How should I structure my node/express/mongodb app?

I'm just curious how people structures their Node.js app?
Usually I create models/ views/ controllers/ and that's simple as that. But I'm kinda new to the Node.js scene and I'm trying to learn as much as I can about how the community works.
Any answer is welcome, thanks!
For what it's worth, my actual setup is this, until I come up (or find) something clearly better:
lib
db
index.js
model.js
...
handler
index.js
whateverMakesSenseForMyParticularWebSite.js
...
router
index.js
model1RestRoutes.js
model2RestRoutes.js
iuRoutes.js
...
config.js (or a folder with multiple files if it makes sense)
server.js (main)
public
css
img
js
test
...
views
...
So yes, models, views, but I do separate routes and actual handlers' implementation. Decoupling, dependency injection all the way. Way more testable/mockable.

Resources