Including remote library with Node.js? - node.js

I've noticed that every time I want to use a package in Node I need to "npm install" it locally and then use the require keyword. I wanted to know if there's a way I could include a remote library kind of like that way we can include remote files using client side html when we use a CDN:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>

require() in node core is synchronous, so there is no way to do it natively (since network i/o is async in node). You'd have to write some function to fetch the resource first and then require() it.

You can't actually supply a URL to "require", but you can of course fetch a remote resource from a URL, including a javascript resource. And then load it locally.
The following answer even links to a "remote_require" that someone wrote to do another kludgy version of this.
how to require from URL in Node.js

If you are trying to use other JavaScript files in your application, you will need to export all of the functions defined by those JavaScript files.
You would export a function like so:
exports.nameOfExport = function(x, y, z) {
// Function content
};
You would then require this file in the file you are trying to use it in with this line:
var myFileName = require('./routes/folder1/myFileName'); // Relative path to required file
If this doesn't answer your question, I suggest going to https://www.npmjs.org/ to search for a package that does what you are trying to do.

Related

Sails.js: can't find variable require (react-bootstrap-datetimepicker)

I'm using Sails js and I want to use a nodejs module.
I also use React js.
I want to use react-bootstrap-datetimepicker in my javascript script.
react-bootstrap-datetimepicker
I installed my module with npm install react-bootstrap-datetimepicker
I tried in config/boostrap.js to add this line var DateTimeField = require('react-bootstrap-datetimepicker');, but DateTimeField isn't recognised in my js script.
Uncaught ReferenceError: DateTimeField is not defined
I also tried to add this line directly in my script, but I have this error:
ReferenceError: Can't find variable: require
And also this one in my script: import DateTimeField from "react-bootstrap-datetimepicker";
I have all these errors in the navigator console.
EDIT 1:
I understand what you said, thank you for your answer.
BUT, for example with react-bootstrap, I can use:
var Input = ReactBootstrap.Input;
var ButtonInput = ReactBootstrap.ButtonInput;
There is exactly the same architecture with react-bootstrap-datetimepicker, so I maybe I can do the same?
var DateTimePicker = ... . DateTimePicker
I tried to include like you said, but it doesn't recognise DateTimePicker.
Here is the doc:
Installation :
npm install react-bootstrap-datetimepicker
Then
javascript
var DateTimeField = require('react-bootstrap-datetimepicker');
render: function() {
return <DateTimeField />;
}
See (examples/) for more details.
And in examples/, the line is:
import DateTimeField from "react-bootstrap-datetimepicker";
Ok, first you have to understand the division of server side and client side javascript, even thought you are using the same language, and you can share libraries, bare in mind, that for client side js you need to supply the user browser with the libraries and scripts it needs, so those have to be in the html you serve the user. When you require any module in sails bootstrap or similar, you are loading the script into the server memory, not serving it to the users browser, that means you can use in the server code, but not in client code.
For you use case, you have to download the library code, and put it in your assets/js folder and if you have the script tags in the layout, sails will automatically inject it there for you, but if not or you are using other template engine like jade, just manually add it.
example:
<html>
....
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/<react-version>/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/<react-version>/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/<version>/react-bootstrap.min.js">
<script src='/js/react-bootstrap-datetimepicker.min.js'></script>
// The other js files that depend on datetimepicker go here
</html>
Now just to be clear, require is a node.js function, node.js is not the same as javascript, its a piece of software with its own functions, thats why you are getting an error related to it when trying to use it in the browser, there is no require method there, so you can't use it, at least not directly. You can use browserify to sort of emulate the node workflow, where you have a node_modules folder and use require on those, browserify will bundle (search for the modules and merge them) and give you a javascript file that you can then link in your html code. That is more setup work, and unless you really need it, because you have a lot of files, i think is not worth the effort.. lets say for just one file using require.
So i think you were misguided by that github repo, because it says npm-install. Just ignore it (unless you use browsefify like i said) and download the link i gave you above ( the .min.js).
So to sumarize, you issue have nothing to do with sails, just link the library in the html you provide to the user, like any other client side script.

Why can't I require files which are available due to app.use?

If a directory has been made available to a node application in the server.js file which sits in the main directory using:
app.use("/scripts",express.static(__dirname + "/scripts"));
and I attempt to use require from a file inside of that directory (/scripts/custom.js) using:
var Testing123 = require('../app/models/article');
Is there a reason this is not possible? and is there a solution to that problem?
Edit: In one of my views (views/tree.ejs) I use:
<script type="text/javascript" src="../scripts/custom.js"></script>
to access my Custom script which sits inside my scripts folder which is made available using express.static, Custom uses a web scraper to scrape articles and present them in circles (in the form of an image, title and link) on views/tree.ejs, I now want custom.js to save each article it creates to a mongodb database but to do so, it needs access to things like my Article Schema hence the problem above.
You cannot because Node.js scripts and browser scripts do not run in the same context. Your app.use call just exposes a /scripts route that serves assets statically on your HTTP Server.
Your scripts/custom.js script seems to be a browser-side script (Because you load it with a script tag inside an ejs view) but you want to use require inside it and this will not work as this is a Node.js function.
Have a look at LearnYouNode which is an excellent Node beginner tutorial so that you will understand how modules work in Node and know a bit more about the separation between server-side and client-side JS.

Meteor.js: How do you require or link one javascript file in another on the client and the server?

1) In node on the backend to link one javascript file to another we use the require statement and module.exports.
This allows us to create modules of code and link them together.
How do the same thing in Meteor?
2) On the front end, in Meteor is I want to access a code from another front end javascript file, I have to use globals. Is there a better way to do this, so I can require one javascript file in another file? I think something like browserify does this but I am not sure how to integrate this with Meteor.
Basically if on the client I have one file
browserifyTest.coffee
test = () ->
alert 'Hello'
I want to be able to access this test function in another file
test.coffee
Template.profileEdit.rendered = ->
$ ->
setPaddingIfMenuOpen()
test()
How can I do this in Meteor without using globals?
Meteor wraps all the code in a module (function(){...your code...})() for every file we create. If you want to export something out of your js file (module), make it a global. i.e don't use var with the variable name you want to export and it'll be accessible in all files which get included after this module. Keep in mind the order in which meteor includes js files http://docs.meteor.com/#structuringyourapp
I don't think you can do this without using globals. Meteor wraps code in js files in SEF (self executing function) expressions, and exports api is available for packages only. What problem do you exactly have with globals? I've worked with fairly large Meteor projects and while using a global object to keep my global helpers namespaces, I never had any issues with this approach of accessing functions/data from one file in other files.
You can use a local package, which is just like a normal Meteor package but used only in your app.
If the package proves to be useful in other apps, you may even publish it on atmosphere.
I suggest you read the WIP section "Writing Packages" of the Meteor docs, but expect breaking changes in coming weeks as Meteor 0.9 will include the final Package API, which is going to be slightly different.
http://docs.meteor.com/#writingpackages
Basically, you need to create a package directory (my-package) and put it under /packages.
Then you need a package description file which needs to be named package.js at the root of your package.
/packages/my-package/package.js
Package.describe({
summary:"Provides test"
});
Package.on_use(function(api){
api.use(["underscore","jquery"],"client");
api.add_files("client/lib/test.js","client");
// api.export is what you've been looking for all along !
api.export("Test","client");
});
Usually I try to mimic the Meteor application structure in my package so that's why I'd put test.js under my-package/client/lib/test.js : it's a utility function residing in the client.
/packages/my-package/client/lib/test.js
Test={
test:function(){
alert("Hello !");
}
};
Another package convention is to declare a package-global object containing everything public and then exporting this single object so the app can access it.
The variables you export NEED to be package-global so don't forget to remove the var keyword when declaring them : package scope is just like regular meteor app scope.
Last but not least, don't forget to meteor add your package :
meteor add my-package
And you will be able to use Test.test in the client without polluting the global namespace.
EDIT due to second question posted in the comments.
Suppose now you want to use NPM modules in your package.
I'll use momentjs as an example because it's simple yet interesting enough.
First you need to call Npm.depends in package.js, we'll depend on the latest version of momentjs :
/packages/my-moment-package/package.js
Package.describe({
summary:"Yet another moment packaged for Meteor"
});
Npm.depends({
"moment":"2.7.0"
});
Package.on_use(function(api){
api.add_files("server/lib/moment.js");
api.export("moment","server");
});
Then you can use Npm.require in your server side code just like this :
/packages/my-moment-package/server/moment.js
moment=Npm.require("moment");
A real moment package would also export moment in the client by loading the client side version of momentjs.
You can use the atmosphere npm package http://atmospherejs.com/package/npm which lets you use directly NPM packages in your server code without the need of wrapping them in a Meteor package first.
Of course if a specific NPM package has been converted to Meteor and is well supported on atmosphere you should use it.

is require.js the right tool (for the job) for "normal" web sites"

I have started building a web site and have used Require.js for selectively loading scripts which I require to implement functionality. What I am experiencing is:
the "main" script has not finished executing (or even downloading) before some of my code uses "require" to load dependencies. What this means is that the require.js config has not run and does not know the locations of my scripts.
because the require.js config has not run by the time my code needs to use it, the "shim" mechanism has not been initialised and cannot be used.
The Common Errors page along with a lot of the issues I seem to be reading about online while trying to solve my own problems seem to suggest that this is not the right tool for the job.
This seems to be useful for single page applications or node.js applications, but not traditional sites where other scripts could be running before require.js has been initialised.
If require.js is not the right tool for the job, is there a right tool for this job? If so then what is?
Are you loading the require.js script asynchronously (with an async='async')? You want requirejs to load synchronously. Once it's loaded, it will load further scripts, like your main.js file, asynchronously. They may all load out of order, but the code will actually get executed in the right order (respecting the declared dependencies).
So in your page template, you would have this:
<script src="/Scripts/require.js" type="text/javascript" data-main="main.js"></script>
That will load RequireJS, and once it's loaded it starts loading your main.js asynchronously. Typically main.js does not define any modules, it just makes use of modules defined in other files. These dependencies are listed in the require() call:
require(["moduleA", "moduleB"], function(A, B){
// Do something with A and B
A.someFunction();
B.someOtherFunction();
});
The files moduleA.js and moduleB.js must wrap their contents inside a define(). In moduleA.js (which depends on module C):
define(["moduleC"], function () {
// Build up an A
var A = ....;
return A;
});
I wonder now if you're wrapping your modules in a define call. Not doing that could explain the out-of-order execution you're experiencing.
RequireJS is a perfectly valid tool on a traditional site, not just on a single-page site.

Node.js to use external JS file?

Actually i'm using node-crawler under Node.js. Then i currently need to use the methods of PHPJS (An External Javascript File). How can i add or include that JS file into NODE.JS environment?
You can download one of the CommonJS files (here: http://phpjs.org/packages/index), save it locally and just require it like a standard NodeJS module:
var php = require('name of file');
php.md5(...)
Just like any other file, except perhaps it will be up a few levels?:
enter code hererequire('../../path/to/whatever.js');

Resources