Including a .js file in node.js - node.js

I am trying to include this script in my app: http://www.movable-type.co.uk/scripts/latlong.html
I have saved it in a file called lib/latlon.js, and I am trying to include it like this:
require('./lib/latlon.js');
How should I go about including a JS library like this?

First of all, you should take a look at the Modules documentation for node.js:
http://nodejs.org/docs/v0.5.5/api/modules.html
The script you're trying to include is not a node.js module, so you should make a few changes to it. As there is no shared global scope between the modules in node.js you need to add all the methods you want to access to the exports object. If you add this line to your latlon.js file:
exports.LatLon = LatLon;
...you should be able to access the LatLon function like this:
var LatLonModule = require('./lib/latlon.js');
var latlongObj = new LatLonModule.LatLon(lat, lon, rad);

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.

Need to call Express like use route using Restify

Expresss.use() accepts 2 parameters
app.use('/abcd', routeHandler);
Restify only supports one
restify.use(routeHandler);
Referring to workaround on https://github.com/restify/node-restify/issues/289
server.use(scopeMiddlewareTo('/prefix', myMiddleware));
I'm trying to use this workaround, but getting below error
{"code":"InternalError","message":"middleware.call is not a function"}
I'm using Typescript, but even the JS code while debugging and middleware.call() is not found.
Basically I have routes in separate files and do not wish to use restify.get(), restify.post() in main.ts. The separate files act as sub-apps.
You can use this package https://www.npmjs.com/package/restify-prefix-route.
var applyPrefix = require('restify-prefix-route');
server.pre(applyPrefix('/v1'));
use this to add prefix in all routes.

Add global function to every execution of NodeJS

In my project folder project I have a file utils.js like this
global.root_path = process.cwd();
global.custom_require = function() {
console.log('custom require called');
}
I would like to include this file in every execution of node so that in every js file in project i can call custom_require, or access global.root_path as I'm doing already with built-in function require.
Do you know if there is a solution (command line options, environment variable or whatever) to achieve this?
UPDATE
I don't want to include utils.js in every file, in that case I wouldn't need to modify global object.
Thanks!
Simply require it. Example app.js:
require('./utils.js');
var express = custom_require('express');
var app = express();
var port = process.env.PORT || 3000;
app.listen(port);
Then, you could just do (in terminal)
node app
As long as you require the code containing the global declarations on it, then you can use those globals from any file that's required after the fact.
You most probably don't want to have a custom "plugin" altering the behavior of all your applications when run locally, thus it'd be best to stay away from that kind of pattern. Instead, you might want to create a module, use npm link on it, and then npm link something in your project's directory, where something is the module name.
Then each project could just add one line like require('something'); at the very beginning. Changing something would immediately impact all the projects which included it, thanks to the behavior in npm link.

How to reference local files in a npm module?

I wrote a simple npm module to precompile my handlebars templates when using django compressor to do post-processing for some client side components and found that I need to ship the npm module with a few js files.
Currently I just assume no one is installing this with the global flag because I've "hard coded" the path to these dependencies in the npm module itself
example layout of my npm module
/
* /bin
* /lib/main.js
* /vendor/ember.js
Now inside main.js I want to use the ember.js file ... currently my hard coded approach looks like this
var emberjs = fs.readFileSync('node_modules/django-ember-precompile/vendor/ember.js', 'utf8');
Again -this only works because I assume you install it local but I'd like to think node.js has a more legit way to get locally embedded files
Anyone know how I can improve this to be more "global" friendly?
What you can do is get the directory of the current file and make your file paths relative to that.
var path = require('path')
, fs = require('fs');
var vendor = path.join(path.dirname(fs.realpathSync(__filename)), '../vendor');
var emberjs = fs.readFileSync(vendor + '/ember.js', 'utf8');
Hope that helps!
One of the great strengths of Node.js is how quickly you can get up and running. The downside to this approach is that you are forced to fit the design patterns it was build around.
This is an example where your approach differs too much from Nodes approach.
Node expects everything in a module to be exposed from the modules exports, including templates.
Move the readFileSync into the django-ember-precompile module, then expose the returned value via a module export in lib/main.js.
Example:
package.json
{
"name": "django-ember-precompile",
"main": "lib/main.js"
}
lib/main.js
module.exports.ember = readFileSync('vendor/ember.js')
vendor/ember.js
You obtain your template via
var template = require('django-ember-precompile').ember
This example can be refined, but the core idea is the same.

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