想了解NodeJS应用程序结构(完整JavaScript堆栈) [英] Want to get crystal clear about NodeJS app structure (Full JavaScript Stack)

查看:166
本文介绍了想了解NodeJS应用程序结构(完整JavaScript堆栈)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一个典型的NodeJS应用程序的结构,因为我读取和查看项目的次数越多,我就越是困惑,特别是对于像这样的问题:(甚至当我更新这个问题时) / p>


  1. 例如,从我所知道的,NodeJS和Express处理服务器的MEAN堆栈

    部分,提供服务器界面等。MongoDB和Angular非常简单。



    但是,业务逻辑应该在哪里去?说如果我有一个包含一个函数的controller.js,

    ,并且route.js文件使用这个控制器函数来绑定请求。 我的问题在
    下,这些文件属于/运行的模块(Express或NodeJS?)


  2. 是NodeJS应用程序的起始点?说index.php是php应用程序的起点,
    ,但是NodeJS应用程序在哪里?我可以看到所有的nodejs项目都有一个名为server.js或
    app.js的文件(包含类似于 module.exports = app; )但是NodeJS如何知道哪个文件
    可以找到并执行?


我是NodeJS上的新功能,express,sequelize.js / mongoose,jade / ejs但是想要开始一个nodejs项目。你能请详细说明每个模块提供的实际功能以及一个完整js堆叠的nodejs应用程序的典型结构的一般介绍?谢谢提前!

解决方案

好的,这是一个相当广泛的问题,我绝对不是专家,但我会我最好的在这里。



TL; DR




  • 路由是控制器,当用户将浏览器导航到应用程序中的某个路径时,它们会指示执行什么逻辑,包括要呈现的视图以及要发送到这些视图的数据

  • 模型只是 - 应用程序中的数据模型

  • module.exports = 告诉一个文件它是什么导出,那就是代码需要执行或从主应用程序文件可访问。

  • require(..)包含一个模块。您可以将其设置为变量,以便稍后调用模块函数,或者只要执行一个函数,如果这是 module.exports 返回。



结合这些技术可以帮助您确定任何应用程序的坚实框架。






长回答



Express 为构建Node.js应用程序提供了一个坚实的框架。节点完全独立于Express,但由于Express的流行程度实际上与之相当。一旦安装,Express可以用于生成一个脚手架Web项目(带有选项),以便您可以根据需要进行构建。



控制器



生成的项目将创建 / routes / index.js ,其中(如果您了解MVC)本质上是您的主要控制器。快递中的路线是这样写的:

  app.get('/ path',function(req,res,next) {..}); 

让我们分解一下:我们的应用程序变量(app)被告知在GET请求中, code>'/ path'执行匿名回调函数,使用 req,res,next 变量(请求,响应,回调分别) 。我觉得很有帮助,想像一个自定义的事件处理程序。



此处重要的是要注意,我们也可以调用 app.post 具有与URL相同的语法相同的语法。



在我们的匿名回调中,我们处理任何传入的数据并呈现视图为用户。这是我的大部分业务逻辑结束的地方,所以在这里不使用匿名功能实际上是有意义的。这是一个基本回调的例子,只是显示一个主页:

  app.get('/',function(req,res ,接下来){

//一些业务逻辑

res.render('views / home');
});

当用户尝试获取我们的应用程序的索引路径( / ),我们简单地渲染我们的 home 视图,从我们项目的根目录中存储视图文件夹。



但是,如果我们想要模块化,以便我们不在我们的主要 app.js server.js



我们使用 module.exports = .. 在我们的模块中告诉我们的服务器究竟要包括什么。在我的控制器中,我导出一个将应用程序作为参数的函数,并使用它来定义我们的路由,如下所示:



控制器/ User.js

  module.exports = function(app){

app.get('用户的功能(req,res){
var users = req.db.collection('users')。find();
if(!users){
console.log no user found);
res.redirect('/');
} else {
res.render('users / index',{users:users});
}
});

};

不要担心 req.db 代码,我将数据库附加到我的应用程序中的请求,但默认情况下不会这样做。只需明白我在这里收到一个用户列表,如果没有,将用户重定向到我的应用程序的索引。



模型



Mongoose为我们提供了一个很好的界面来编写模型。使用猫鼬,写作模型是三步的过程:




  • 定义模式

  • 定义模型逻辑

  • 生成和导出模型



这是一个用户模型:



Models / User.js

  var mongoose = require('mongoose'),
userSchema = new mongoose.Schema({

name:{type:String,required :true},
joinDate:{type:Date,default:date.now}

}),
User = mongoose.model('user',userSchema);

module.exports = user;

服务器应用



module.exports 用于帮助我们为我们的代码库定义一些模块化。当我们运行节点应用程序时,我们最终会运行一个单一的JavaScript文件(您已经看到该文件具有 server.js 应用程序。 JS )。



为了使这个文件不会变得太大,有多种型号和路线,我们使用 require(module)来自其他JS文件的代码。在我们的例子中, module 将是我们想要的模块的路径。如果您有以下文档结构:

 控制器
- User.js
|模型
- User.js
|查看
app.js

要从应用程序中包含您的用户控制器.js ,你会写: require('./ Controllers / User')。由于我们的控制器模块只是导出函数,所以我们可以在require语句之后立即调用该函数,只需在末尾添加括号(需要任何参数)即可。包括我的控制器如下所示:



require('./ Controllers / User')(app) p>

我正在传递实际的应用程序,因为我的模块(下面)只是导出一个将业务逻辑添加到我的应用程序路由的函数。这只需要被调用并且永远不会被使用,所以我不会将控制器作为一个变量来捕获以后调用方法。



包括模型有所不同,因为我们可能希望执行我们的模型定义的一些操作。我们可以通过更改我们的需求代码来实现这一点:



var User = require('./ Models / User'); / code>



现在我们可以随时调用我们的用户模型的方法。 Mongoose为我们提供了大量免费的基本功能:



User.find({},function(err,users){..}) ;



上述功能将会找到我们所有的用户,然后执行一个潜在的错误的匿名函数(如果没有问题,则为null),然后是JSON格式的用户列表。相当漂亮。



结合所有这些概念是如何使用Express和Node.js创建基本的Web应用程序。如果有什么我可以澄清我如何使用快递,请在评论中通知我。这是非常表面层次的知识,我建议挖掘文档并查看插件来扩展您的应用程序的功能。祝你好运!


I would like to know the structure of a typical NodeJS app, because the more I read and see the projects, the more confused I am, specifically for questions like these:(or even more when i update this question.)

  1. Take the MEAN stack for example, from what I know, NodeJS and Express takes care of the server
    part, providing the server interface, etc. MongoDB and Angular is pretty straightforward.

    But where should the business logic go? Say if I have a controller.js which contains a function,
    and the route.js file bind the request with this controller function. My question is under which module these files belongs to/runs under (The Express or NodeJS ?)

  2. Where is the starting point of a NodeJS app? Say index.php is the starting point of a php app, but where is it for NodeJS app? I can see all the nodejs projects has a file called server.js or app.js, etc.(contains something like module.exports = app;) But how can NodeJS know which file to find and execute it?

I am a fresh noob on NodeJS, express, sequelize.js/mongoose, jade/ejs but want to get started on a nodejs project. Could you guys please elaborate the actual function that each module provides and a general introduction of the typical structure for a full js stacked nodejs app? Thanks in advance!

解决方案

Alright, this is a pretty broad question and I'm definitely no expert, but I'll do my best here.

TL;DR

  • routes are controllers that tell what logic to execute when a user navigates their browser to a certain path within your app, including which views to render and what data to send to those views
  • models are just that - data models within your application
  • module.exports = tells a file what exactly it "exports", that is what code needs to be executed or accessible from your main app file.
  • require(..) includes a module. You can set this on a variable so that you may call module functions later, or simply execute a function if that is all that module.exports returns.

Combining these techniques can help you nail down a solid framework for any of your applications.


Long Answer

Express provides a solid framework for structuring your Node.js application. Node is completely independent of Express, but because of how popular Express is they practically go hand-in-hand. Once installed, Express can be used to generate a scaffold web project (with options) for you to build on top of if you'd like.

Controllers

A generated project will create /routes/index.js, which (if you understand MVC) is essentially your main controller. A route in express is written as so:

app.get('/path', function(req, res, next){ .. } );

Lets break that down: our application variable (app) is being told that on a GET request to '/path' to execute an anonymous callback function with req, res, next variables (request, response, callback respectively). I find it helpful to think of this like a custom event handler.

Its important to note at this point that we could also call app.post with the same syntax for posts to a URL as opposed to gets.

Within our anonymous callback, we handle any incoming data and render a view for the user. This is where most of my business logic ends up, so it actually makes sense to NOT use anonymous functions here. Here's an example of a basic callback that just displays a homepage:

app.get('/', function(req, res, next){

    //some business logic

    res.render('views/home');
});

When the user tries to GET the index path of our application (/), we simply render our home view that, from the root of our project, is stored in a views folder.

But what if we want to modularize this so that we aren't declaring all of our routes in our main app.js or server.js?

We use module.exports = .. in our modules to tell our server what exactly to include. In my controller, I export a single function that takes the application as an argument and uses that to define our routes like so:

Controllers/User.js

 module.exports = function(app){

    app.get('/users', function(req, res){
        var users = req.db.collection('users').find();
        if (!users) {
            console.log("no users found");
            res.redirect('/');
        } else {
            res.render('users/index', {users : users});
        }
    });

};

Don't worry about the req.db code, I attach the database to the request in my application but that isn't done by default. Simply understand that I'm getting a list of 'users' here, and redirecting the user to the index of my app if there aren't any.

Models

Mongoose provides us with a great interface for writing models. With mongoose, writing models is a three step process:

  • Define a schema
  • Define model logic
  • Generate and export the model

Here is an example of a User model:

Models/User.js

var mongoose = require('mongoose'),
    userSchema = new mongoose.Schema({

        name: { type: String, required: true },
        joinDate: {type: Date, default: date.now }

    }),
    User = mongoose.model('user', userSchema);

module.exports = user;

Server App

module.exports is used to help us define some modularity to our codebase. When we run a node application, we're ultimately running a single JavaScript file (you've already seen that file with server.js or app.js).

To keep this file from getting too big with multiple models and routes, we use require(module) to include code from other JS files. module in our case would be a path to the module we want to require. If you have the following doc structure:

| Controllers
    - User.js
| Models
    - User.js
| Views
app.js

To include your user controller from app.js, you would write: require('./Controllers/User'). Since our controller modules simply export functions, we can call that function immediately after our require statement by simply adding parentheses at the end (with whatever parameters are required). Including my controllers looks like so:

require('./Controllers/User')(app)

I'm passing in the actual app, because my module (below) simply exports a function that adds business logic to my app's routes. This only needs to be called and never used, so I don't capture my controller as a variable to call methods on later.

Including models is a little different, since we may want to perform some operation that our model defines. We can do this by changing up our require code just a bit:

var User = require('./Models/User');

Now we can call methods of our User model whenever. Mongoose gives us a lot of base functionality for free:

User.find({}, function(err, users){ .. });

The above function will go find all of our users, and then execute an anonymous function with a potential err (is null if no issues) and then a list of our users in JSON format. Pretty nifty.

Combining all of these concepts is how you create a basic web application using Express and Node.js. Please let me know in the comments if there's anything I can clarify about how I use Express. This is very surface level knowledge, and I suggest digging into documentation and looking at plugins to extend the capabilities of your apps. Good luck!

这篇关于想了解NodeJS应用程序结构(完整JavaScript堆栈)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆