Node.js to use external JS file? - node.js

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');

Related

How should I load a file that is inside my own module?

Current code in /config/index.js
const options = (require('js-yaml')).safeLoad(
(require('fs')).readFileSync(`./config/default-config.yaml`, "utf8"));
module.exports = options;
Works fine. Until I publish and use it in my other project. Then it's unable to find the file (naturally) as ./config/default-config.yaml doesn't exist in that project.
The only option I can think of involves checking to see if the file exists at that path, then trying to load it from node_modules/#company/alpha-gamma/config/default-config.yaml. This seems really hacky.
The config object is large, 200+ keys. I don't think it belongs in the code.
What's the best solution for loading a file that exists inside your module? I need to be able to load it for unit tests before publishing and load it at runtime when the library is required by another module.
Maybe the best alternative is to use json since I can then use the require module to load it in, instead of fs.
While I originally suggested utilizing __dirname as a valid option, I was wrong. Calling process.cwd() to fetch the application root and building the path off of that is the best approach.
As documented here:
Proper way to reference files relative to application root in Node.JS

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.

Including remote library with 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.

ExpressJS - Auto Compiling CoffeeScript For Front End

Node.js is simply awesome. And it seems as though Express.js is the Sinatra of Ruby for Node.js.
I love how simple Express is. To make things better, I configured it to use CoffeeScript in the backend. I am wondering if there is a way to use auto compile and serve coffeescript files.
Currently I am writing them in a public src folder, and compiling it to a lib folder. I would like some thing a little simpler.
Some thing like
[server]/coffee/file.js -> will provide the compled source of [server]/coffee/file.coffee?
I found a package, express-coffee which is as old as Node I guess and not updated in 2 years :(.
Is there any specific way to compile front end coffee script to JS without manual interaction?
I use connect-coffee-script. And this how I use it (in coffeescript) :
app.use require('connect-coffee-script')
src : "#{__dirname}/client/assets/coffee"
dest : "#{__dirname}/client/public/js"
prefix : '/js'
Just use coffee-middleware (or similar) and you can process browser requests for .js files, locate the corresponding .coffee files on the server's filesystem, transpile them to javascript, and sent the javascript code down to the browser.

Resources