node.js - 如何构建 Node/Angular/Socket.io 项目?

标签 node.js angularjs socket.io project

我正在开发一个使用 AngularJS 和 Socket.io 的项目。我找到了 this非常好的集成示例。

这是项目结构:

app.js                  --> app config
bower.json              --> for bower
package.json            --> for npm
public/                 --> all of the files to be used in on the client side
  css/                  --> css files
    app.css             --> default stylesheet
  img/                  --> image files
  js/                   --> javascript files
    app.js              --> declare top-level app module
    controllers.js      --> application controllers
    directives.js       --> custom angular directives
    filters.js          --> custom angular filters
    services.js         --> custom angular services
  bower_components/
    angular/            --> angular.js
    angular-socket-io/  --> socket.io adapter for angular
routes/
  index.js              --> route for serving HTML pages and partials
  socket.js             --> serve content over a socket
  api.js                --> serve JSON to our AngularJS client
views/
  index.jade            --> main page for app
  layout.jade           --> doctype, title, head boilerplate
  partials/             --> angular view partials (partial jade templates)
    partial1.jade
    partial2.jade

在 app.js 中:

var express = require('express'),
    routes = require('./routes'),
    api = require('./routes/api'),
    socket = require('./routes/socket');

...

// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// JSON API
app.get('/api/name', api.name);

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

// Socket.io Communication
io.sockets.on('connection', require('./routes/socket'));

现在,虽然通常我只是将服务器逻辑放在 app.js 中,但这里的逻辑似乎分为 api.jssocket。 jsindex.js - 我非常喜欢这个。

但是,假设在 socket.js 中我需要使用在 api.js 中定义的东西。我应该添加一个 var api = require( './api');socket.js?

最佳答案

我最终创建了模块/对象,将所有内容导入 app.js 并通过相互引用传递它们(需要时)..

  var mashup = require('./routes/mashupModule'),
  socket = require('./routes/socketModule'),
  browser = require('./routes/browserModule');

  socket.init(server, browser, mashup);
  browser.init(socket, mashup);

不确定这是否是在代码中进行某种分离的最佳方式。我习惯了 Java,这很糟糕,在 JS 中它通常是一个大源文件。

关于node.js - 如何构建 Node/Angular/Socket.io 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17491758/

相关文章:

node.js - 使用 Redis 和 Socket.io 在 Laravel 5.2 中进行事件广播

node.js - 我可以使用 webpack 的热模块重新加载和 sailsjs 吗?

javascript - 在 Angular 中将响应从工厂返回到 Controller

node.js - 如何防止每条新推文触发 Twitter 流中的回调?

websocket - 保持与 Socket.io 的连接

javascript - 日期和时间差以及平均时间

javascript - 将 csurf 与 react 服务器一起使用

node.js - 在NodeJS端使用SocketIo读取数据?

javascript - 在 ng-click 函数中编码对象值

angularjs - 在没有专用 WebDriver 实现的浏览器上运行 Protractor?