How can I independently use submodule of a module in nodejs - node.js

I wish to use the 'utils-merge' node module already present as a dependency of express 4.12.3. I have express installed in my server application.
I have tried:
var merge = require('express/utils-merge');
and
var merge = require('utils-merge');
But it throws error 'Cannot find module'.

It is possible to do it using:
var merge = require('express/node_modules/utils-merge');
However, the standard practice is to explicitly require all of your dependencies so that you can directly require them.

You have to use relative path to submodule after parent module name (see documentation):
var merge = require('express/node_modules/utils-merge');

Related

How to set a default/fallback scope on package names with Node require()

I am using a particular module in my Node code:
const example = require('example');
However this module is slow to be updated, so I have forked it and published it with my updates under my own scope on npmjs.com. However now to use my own module, I must change every use in my code:
const example = require('#my-username/example');
The problem with this is that I will have to commit a bunch of changes throughout many files to rename the module, then when upstream merges my changes into the official version I will have to update my code again to remove the scope operator from require() across all those files, then add it back if I have more changes that are slow to be accepted, and so on.
Is there a way that I can tell Node or NPM that if require() can't find a module with no scope in the name, to then check all the #scope folders in node_modules to see if there's a match there?
If that were possible then I would only need to update package.json with the relevant package version and the code itself could remain unchanged as I switch between my fork and the official version.
you can implement it using module-alias
This will slow down your startup, but let you write all this logic for every requires you make in your application.
const moduleAlias = require('module-alias')
// Custom handler function (starting from v2.1)
moduleAlias.addAlias('request', (fromPath, request, alias) => {
console.log({
fromPath,
request,
alias,
});
return __dirname + '/my-custom-request'
})
require('request')

Nodejs is confilicting with Requirejs when using require

I am new to requirejs I want to get rid of the conflict when calling require('fs').
I have read on http://requirejs.org/docs/faq-advanced.html that I can use a config that will combine requirejs with mainjs into a new js file but I am not sure where to put that piece of code to make it work.
Thanks in advance.
If you want to use require.js with node you should follow the instructions for node.
Basically you have to npm i requirejs and then (directly from the docs):
var requirejs = require('requirejs');
var foo = requirejs('foo');
var bar = requirejs('bar');

Parse.com adding node.js modules to Cloud

I'm trying to add gm module to my cloud. Since parse is not a node.js environment I made small changes over other modules I used, but gm module requires so much node core module. Do I have to push all of the sub modules to parse. Also how can I add the core modules. Changing require('xxx') to require('xxx/index.js') or require('xxx/xxx.js') failed.
These are the modules I could find where gm is depended and changed these files. I did include all the files in the modules only changed the following ones.
- gm/index.js
- events/events.js
- util/util.js
- stream/index.js
- emitter/index.js (also depends on util)
- asynclist/index.js
- eventproxy/index.js
changing all of these gives error
Result: Error: Module ./lib/eventproxy not found
at libs/eventproxy/index.js:1:18
at libs/asynclist/index.js:1:18
at libs/emitter/index.js:1:17
at libs/stream/index.js:22:15
at libs/gm/index.js:6:14
at main.js:118:14
// This error is caused by ./lib/eventproxy.
// It must be cloud/libs/asynclist/node_modules/eventproxy/lib/eventproxy.js
// Parse doesn't recognize './' as this folder in cloud code
where gm/index.js's require part is
var Stream = require('cloud/libs/stream/index.js').Stream;
var EventEmitter = require('cloud/libs/events/events.js').EventEmitter;
var util = require('cloud/libs/util/util.js');
My cloud folder structure is
cloud/libs/gm
cloud/libs/events
cloud/libs/util
cloud/libs/stream
cloud/libs/emitter
cloud/libs/asynclist
cloud/libs/eventproxy
EDIT: I found more dependencies. According to this, gm has 36 dependent libraries and I clearly need a simple solution.
EDIT: for the relative path problem with parse, this is a solution but as I said I need a simple way for the whole problem.

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