require().server. Require with a dot in the statement - node.js

var WebSocketServer = require('websocket').server;
I came across this in some NodeJS code and I don't believe I have ever seen a require with a dot in the statement like this ever before. Is the dot perhaps loading just a portion of the websocket module or is there another meaning to it?
Thanks in advance...

Out of the object exported by module.exports you are taking the object referred by server key.
If you look at the code you could see that it is requiring this module

Related

nodejs include required packages in all route files using require() function

Hi I'm new to nodeJs and currently developing a Rest API using node.I'm planning to develop it with a good folder structure, so I can scale it up easily. There I'm using several route files according to the business logic.
ex :- authRoutes,profileRoutes,orderRoutes ......
Currently in every single route file I had to include following codes
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var passport = require('passport');
My problem is , Is it totally fine to use above code segments in all the route files( I'm concerning about the code optimisation/coding standards and execution speed ) or is there any better way to do this.
It's better if you can explain the functionality of require() function.
Thanks
In my experience, this is very standard to do. I suggest reading this question and answer to learn more about the way it affects the speed of your programs.
TL;DR of require()
When your lines of code are ran that include a variable that exists because of a require(), for instance
var https = require('https');
https.get(url, function(response) {...});
The compiler reads it and goes into the https module folder, and looks for the .get function.
However, if you are trying to require() a certain JavaScript file, such as analysis.js, you must navigate to that file from the file you are currently in. For instance, if the file you want is on the same level as the file you are in, you can access it like this:
var analysis = require('./analysis.js');
//Let analysis have a function called analyzeWeather
analysis.analyzeWeather(weather_data);
These lines of code are a little different from above. In this require() statement, we are saying grab the .js file with this name, analysis. Once you require it, you can access any public function inside of that analysis.js file.
Edits
Added require() example for .js file.

What is the purpose of the `(app)` in `require(controller)(app)`?

I'm new to node, blah blah
I'm looking through some code I found, and encountered the lines
var app = express();
var glob = require('glob');
var controllers = glob.sync(config.root + '/app/controllers/*.js');
controllers.forEach(function (controller) {
require(controller)(app);
});
I understand that this goes and gets all the filenames of every file in /app/controllers/ that ends with .js, and sticks them in an array, then iterates over each one and calls a require on it. Makes sense, and looks like a nice way of not requiring each one individually. My question is what's that last (app) for? I tried looking at node documentation, but there is no require()() function. editing out the (app) leaves the code working fine with no errors, but doesn't load the controllers. If I had to take a guess, is it 'multiplying' the app by the found controller? Why would app.require(controller) not be a suitable option?
Thanks in advance
require is a part of node and is how modules are loaded. When you edit out the (app), it is probably still loading the controllers but because you haven't passed the app object over to each controller, they fail silently or return a controller object that doesn't work.
So something in the controller (probably a route being created or other similar stuff) needs to know about the app object and it has to be passed into the controller because app isn't in the global scope. You may want to review the node docs for module and globals as those will probably clear up WAY more than just this one question.
In my estimation we will have:
/* some-controller-file.js */
module.exports = function (app) {
/* do things with `app` */
}
So this allows you to use the created app inside of the controllers probably so you can attach routes.

what does var io = require('../..')(server) do?

I've build the project https://github.com/Automattic/socket.io/tree/master/examples/chat locally and it is working great. However, it would be nice to understand a little more about how a socket application works.
In the main startup script one of the modules that is pulled in with require is
var io = require('../..')(server)
what does require('../..') do?
thanks!
When a path to a directory is given to require, it will implicitly look for an index.js in that directory.
In this case, it's the equivalent of
var socket = require("../../index.js");
var io = socket(server);
In the example provided, they're just using some shorthand and throw away the intermediate value returned by the call to require.
Check out the module.require docs for more info.
Here, in your code
require('../..');
Will add File form the path, which have used SOCKET.IO, as you can see that you have not added Socket.io module.
Also, if no specific path give for file or folder, Module require will try to load index.js or index.node. if no such file exist then it will give error.

node.js http.connections

I am looking over node.js code and can't understand some of it. Please help me with it.
var http = require("http"),
server = http.createServer(function(req,res) {});
......
if(MaxUserCheck <1 ){
server.watcher.stop();
logmsg(level1, server.connections);
}
For the above code,
what is "watcher" and how to use it?
"server.connections" - what is this? and how to use it?
I have seen using server module as
server.on('request', function (req,res){};
...
server.listen(52273, function(){};
and I can understand as above, but using as "server.connections" can't understand and haven't seen it use like that.
I looked up on node.js manual but doesn't explain it.(http://nodejs.org/api/)
It seems that "server.connections" returns how many clients connected to our server..(Server uses Fugue for multi clients)
where can I find the usage of "server.connections" and "server.watcher"
Thank you.
These two syntaxes might have been used/required in other directories. If I export this module to a different file and say require('watcher') there , it will work.however I'm not sure what watcher is used but it could be webwatcher module.

Nodejs + CoffeeScript + Mongoose : Define Module?

I'm trying to create a little application to store snippets of code using nodejs and mongodb
I'm using Coffeescript to write the app.
The problem is, i want to separate the code in modules
so i create this folder structure
/app
/lib
/models
/routes
core.coffee
The core.coffe is the "server" app using expressjs
so in this file i have
mongoose = module.exports.mongoose = require 'mongoose'
app = module.exports.app = express.createServer()
Snippet = module.exports.Snippet = require __dirname+'/lib/models/Snippet'
#App configurations
routes = require(__dirname+'/lib/routes/general')
In lib/models/Snippet
mongoose = module.parent.exports.mongoose
Snippet = new mongoose.Schema
title:
type: String
default:'Title'
mongoose.model 'Snippet',Snippet
exports.Snippet = mongoose.model 'Snippet'
In /lib/routes/general.coffee
app = module.parent.exports.app
mongoose = module.parent.exports.mongoose
Snippet = module.parent.exports.Snippet
app.get '/test', (req,res)->
snip = new Snippet()
res.send snip
But this don't work i get the following error message
TypeError: object is not a function
at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
How can I accomplish that?
I see a noteworthy typo:
Snippet = module.exports.Snippt = require __dirname+'/lib/models/Snippet'
Change module.exports.Snippt to module.exports.Snippet.
Let's start by looking at how you're using require. It looks like you're trying to load all the project's requirements in core.coffee, and then re-export them elsewhere. That's an odd way of doing it, most people just require those libraries in each module that needs them (for now at least, see the end of my answer).
For example, you need mongoose in lib/models/Snippet, so just require it there:
lib/models/Snippet:
mongoose = require 'mongoose'
Next, there's no need to use __dirname to require a relative path, require copes fine with a path starting with ./:
require './lib/models/Snippet'
I still wasn't able to get the code to work cleanly (I'm guessing we're not seeing the full code), but it might be enough to set you on the right path.
Finally, if you want to go down the route of exporting everything on the main module can I suggest taking a look at dave-elkan's layers project. The plain version doesn't support coffeescript, but I've created a fork that does.
It's very lightweight, and makes almost no assumptions about your project structure. The basic idea is that you give layers() your express app object and a directory. Layers will scan that directory and set up any subdirectories as layers on your app object.
In your case you'd pass in a rootPath: __dirname + '/lib' and your app object would get app.models.Snippet and app.routes.general added onto it. That's still not quite how I'd structure it, but you might be able to come up with something that matches your style from there.

Resources