How to call a Meteor method from the command line - meteor

I have a Meteor app and want to call a server method from the command line, so that I can write a bash script to perform scheduled operations.
Is there any way to either call a method directly, or submit a form which will then trigger server-side code?
I've tried using curl to call a method, but either it's not possible or I'm missing something basic. This doesn't work:
curl "http://localhost:3000/Meteor.call('myMethod')"
nor does:
curl -s -d "http://localhost:3000/imports/api/test.js" > out.html
where test.js:
var test = function(){
console.log('hello');
}
I thought of using a form but I can't think how to create a submit event because the Meteor client uses template events that then call server methods.
I'll be very grateful for any help! This feels like it should be a simple thing but has me stumped.
Edit: I've also tried phantomjs and slimerjs as run through casperjs.
phantomjs is no longer maintained and generates an error:
TypeError: Attempting to change the setter of an unconfigurable property.
https://github.com/casperjs/casperjs/issues/1935
slimerjs errors with Firefox 60 and I can't figure out how to 'downgrade' back to the supported 59, and the option to disable automatic updates of Firefox no longer seems to exist. The error is:
c is undefined
https://github.com/laurentj/slimerjs/issues/694

You could make use of the node ddp package to call the Meteor method in an own js file that you created with a specific script. From there you can pipe all outs to wherever you want.
Let's assume the following Meteor method:
Meteor.methods({
'myMethod'() {
console.log("hello console")
return "hello result"
}
})
The upcoming steps will let you call this method from another shell, assuming your Meteor application is running.
1. Install ddp in your global npm directory
$ meteor npm install -g ddp
2. Create the script to call your method in your test directory
$ mkdir -p ddptest
$ cd ddptest
$ touch ddptest.js
Place the ddp script code into the file with the editor or command of your choice.
(The follwing code is freely taken from the package's readme. Feel free to configure to your needs.)
ddptest/ddptest.js
var DDPClient = require(process.env.DDP_PATH);
var ddpclient = new DDPClient({
// All properties optional, defaults shown
host : "localhost",
port : 3000,
ssl : false,
autoReconnect : true,
autoReconnectTimer : 500,
maintainCollections : true,
ddpVersion : '1', // ['1', 'pre2', 'pre1'] available
// uses the SockJs protocol to create the connection
// this still uses websockets, but allows to get the benefits
// from projects like meteorhacks:cluster
// (for load balancing and service discovery)
// do not use `path` option when you are using useSockJs
useSockJs: true,
// Use a full url instead of a set of `host`, `port` and `ssl`
// do not set `useSockJs` option if `url` is used
url: 'wss://example.com/websocket'
});
ddpclient.connect(function(error, wasReconnect) {
// If autoReconnect is true, this callback will be invoked each time
// a server connection is re-established
if (error) {
console.log('DDP connection error!');
console.error(error)
return;
}
if (wasReconnect) {
console.log('Reestablishment of a connection.');
}
console.log('connected!');
setTimeout(function () {
/*
* Call a Meteor Method
*/
ddpclient.call(
'myMethod', // namyMethodme of Meteor Method being called
['foo', 'bar'], // parameters to send to Meteor Method
function (err, result) { // callback which returns the method call results
console.log('called function, result: ' + result);
ddpclient.close();
},
function () { // callback which fires when server has finished
console.log('updated'); // sending any updated documents as a result of
console.log(ddpclient.collections.posts); // calling this method
}
);
}, 3000);
});
The code assumes that your app runs on localhost:3000, note that there is no conncection close on errors or undesired behavior.
As you can see at the top, the file imports your globally installed ddp package. Now in order to get it's path without using additional tools, just pass an environment variable (process.env.DDP_PATH) and let your shell handle the path resolving.
In order to get the installation path you can use npm root with the global flag.
Finally call your script via:
$ DDP_PATH=$(meteor npm root -g)/ddp meteor node ddptest.js
Which will give you the following output:
connected!
updated
undefined
called function, result: hello result
And logs hello console to the open session that is running your meteor app.
Edit: A note on using this in production
If you want to use this script in production you have to use the shell commands without the meteor command but using your installation of node and npm.
If you get in trouble with paths use process.execPath to find your node binary and npm root -g to find your global npm modules.

You can check out this documentation: Command Line | meteor shell.
While your meteor app is running, you can execute meteor shell to start an interactive console. In the console, you can do Meteor.call(...).
So if you want to write a script with using meteor shell, you might need to pipe the script file for meteor shell. Like,
$ meteor shell < script_file
See also the answer of "How can I pipe a command into the meteor shell?"

Related

How can you add :// to your file? [duplicate]

How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?
Go to Start then in Find type regedit -> it should open Registry editor
Click Right Mouse on HKEY_CLASSES_ROOT then New -> Key
In the Key give the lowercase name by which you want urls to be called (in my case it will be testus://sdfsdfsdf) then Click Right Mouse on testus -> then New -> String Value and add URL Protocol without value.
Then add more entries like you did with protocol ( Right Mouse New -> Key ) and create hierarchy like testus -> shell -> open -> command and inside command change (Default) to the path where .exe you want to launch is, if you want to pass parameters to your exe then wrap path to exe in "" and add "%1" to look like: "c:\testing\test.exe" "%1"
To test if it works go to Internet Explorer (not Chrome or Firefox) and enter testus:have_you_seen_this_man this should fire your .exe (give you some prompts that you want to do this - say Yes) and pass into args testus://have_you_seen_this_man.
Here's sample console app to test:
using System;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
if (args!= null && args.Length > 0)
Console.WriteLine(args[0]);
Console.ReadKey();
}
}
}
Hope this saves you some time.
The MSDN link is nice, but the security information there isn't complete. The handler registration should contain "%1", not %1. This is a security measure, because some URL sources incorrectly decode %20 before invoking your custom protocol handler.
PS. You'll get the entire URL, not just the URL parameters. But the URL might be subject to some mistreatment, besides the already mentioned %20->space conversion. It helps to be conservative in your URL syntax design. Don't throw in random // or you'll get into the mess that file:// is.
If anyone wants a .reg file for creating the association, see below:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\duck]
"URL Protocol"=""
[HKEY_CLASSES_ROOT\duck\shell]
[HKEY_CLASSES_ROOT\duck\shell\open]
[HKEY_CLASSES_ROOT\duck\shell\open\command]
#="\"C:\\Users\\duck\\source\\repos\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0\\ConsoleApp1.exe\" \"%1\""
Pasted that into notepad, the file -> save as -> duck.reg, and then run it. After running it, when you type duck://arg-here into chrome, ConsoleApp1.exe will run with "arg-here" as an argument. Double slashes are required for the path to the exe and double quotes must be escaped.
Tested and working on Windows 11 with Edge (the chrome version) and Chrome
There is an npm module for this purpose.
link :https://www.npmjs.com/package/protocol-registry
So to do this in nodejs you just need to run the code below:
First Install it
npm i protocol-registry
Then use the code below to register you entry file.
const path = require('path');
const ProtocolRegistry = require('protocol-registry');
console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
protocol: 'testproto', // sets protocol for your command , testproto://**
command: `node ${path.join(__dirname, './index.js')} $_URL_`, // $_URL_ will the replaces by the url used to initiate it
override: true, // Use this with caution as it will destroy all previous Registrations on this protocol
terminal: true, // Use this to run your command inside a terminal
script: false
}).then(async () => {
console.log('Successfully registered');
});
Then suppose someone opens testproto://test
then a new terminal will be launched executing :
node yourapp/index.js testproto://test
It also supports all other operating system.

How can I install Qt 5.2.1 from the command line in Cygwin?

$ wget --quiet http://download.qt-project.org/official_releases/qt/5.2/5.2.1/qt-opensource-windows-x86-msvc2012_64_opengl-5.2.1.exe
$
As seen above, I first downloaded the Qt package for Visual Studio in a Cygwin Bash shell.
A sidenote: The Qt library packaged within Cygwin is not useful for me because I need to use the Visual Studio C++ compiler.
First I set the correct permissions on the file
$ chmod 755 qt-opensource-windows-x86-msvc2012_64_opengl-5.2.1.exe
If I start it like this
$ ./qt-opensource-windows-x86-msvc2012_64_opengl-5.2.1.exe
a graphical window (GUI) is shown but that is not what I want as I would later like to have the installation procedure written into a Bash script that I could run in Cygwin.
If I add the option --help, like this
$ ./qt-opensource-windows-x86-msvc2012_64_opengl-5.2.1.exe --help
a new terminal window is opened with the following text
Usage: SDKMaintenanceTool [OPTIONS]
User:
--help Show commandline usage
--version Show current version
--checkupdates Check for updates and return an XML file describing
the available updates
--updater Start in updater mode.
--manage-packages Start in packagemanager mode.
--proxy Set system proxy on Win and Mac.
This option has no effect on Linux.
--verbose Show debug output on the console
--create-offline-repository Offline installer only: Create a local repository inside the
installation directory based on the offline
installer's content.
Developer:
--runoperation [OPERATION] [arguments...] Perform an operation with a list of arguments
--undooperation [OPERATION] [arguments...] Undo an operation with a list of arguments
--script [scriptName] Execute a script
--no-force-installations Enable deselection of forced components
--addRepository [URI] Add a local or remote repo to the list of user defined repos.
--addTempRepository [URI] Add a local or remote repo to the list of temporary available
repos.
--setTempRepository [URI] Set a local or remote repo as tmp repo, it is the only one
used during fetch.
Note: URI must be prefixed with the protocol, i.e. file:///
http:// or ftp://. It can consist of multiple
addresses separated by comma only.
--show-virtual-components Show virtual components in package manager and updater
--binarydatafile [binary_data_file] Use the binary data of another installer or maintenance tool.
--update-installerbase [new_installerbase] Patch a full installer with a new installer base
--dump-binary-data -i [PATH] -o [PATH] Dumps the binary content into specified output path (offline
installer only).
Input path pointing to binary data file, if omitted
the current application is used as input.
I don't know how to continue from here. Do you know how I could install the Qt 5.2.1 library (for Visual Studio) from the Bash shell in Cygwin?
Update: The advantage of writing the build script for a Cygwin environment is that commands like git, wget, and scp are available. This Stackoverflow answer describes how to invoke the MSVC compiler from a Cygwin bash script. Note, that the Qt application I'm building is not going to have any dependency on Cygwin.
I didn't test with Cygwin but I successfully installed Qt5.5 using a script. To do so, you must use the --script line of the normal installer.
.\qt-opensource-windows-x86-msvc2013_64-5.5.1.exe --script .\qt-installer-noninteractive.qs
Here's an example of qt-installer-noninteractive.qs file I used in the command above
function Controller() {
installer.autoRejectMessageBoxes();
installer.installationFinished.connect(function() {
gui.clickButton(buttons.NextButton);
})
}
Controller.prototype.WelcomePageCallback = function() {
gui.clickButton(buttons.NextButton);
}
Controller.prototype.CredentialsPageCallback = function() {
gui.clickButton(buttons.NextButton);
}
Controller.prototype.IntroductionPageCallback = function() {
gui.clickButton(buttons.NextButton);
}
Controller.prototype.TargetDirectoryPageCallback = function() {
gui.currentPageWidget().TargetDirectoryLineEdit.setText("C:/Qt/Qt5.5.1");
gui.clickButton(buttons.NextButton);
}
Controller.prototype.ComponentSelectionPageCallback = function() {
var widget = gui.currentPageWidget();
widget.deselectAll();
widget.selectComponent("qt.55.win64_msvc2013_64");
// widget.selectComponent("qt.55.qt3d");
// widget.selectComponent("qt.55.qtcanvas3d");
// widget.selectComponent("qt.55.qtquick1");
// widget.selectComponent("qt.55.qtscript");
// widget.selectComponent("qt.55.qtwebengine");
// widget.selectComponent("qt.55.qtquickcontrols");
// widget.selectComponent("qt.55.qtlocation");
gui.clickButton(buttons.NextButton);
}
Controller.prototype.LicenseAgreementPageCallback = function() {
gui.currentPageWidget().AcceptLicenseRadioButton.setChecked(true);
gui.clickButton(buttons.NextButton);
}
Controller.prototype.StartMenuDirectoryPageCallback = function() {
gui.clickButton(buttons.NextButton);
}
Controller.prototype.ReadyForInstallationPageCallback = function()
{
gui.clickButton(buttons.NextButton);
}
Controller.prototype.FinishedPageCallback = function() {
var checkBoxForm = gui.currentPageWidget().LaunchQtCreatorCheckBoxForm
if (checkBoxForm && checkBoxForm.launchQtCreatorCheckBox) {
checkBoxForm.launchQtCreatorCheckBox.checked = false;
}
gui.clickButton(buttons.FinishButton);
}
The tricky part was to found the id of the components! I was able to found the right id qt.55.win64_msvc2013_64 by adding the flag --verbose and installing it normally with the UI and stopping at the last page; all the ids that you selected for installation are there.
There is slightly more information in this answer if you need more details.
EDIT (29-11-2017): For installer 3.0.2-online, the "Next" button in the "Welcome" page is disabled for 1 second so you must add a delay
gui.clickButton(buttons.NextButton, 3000);
EDIT (10-11-2019): See Joshua Wade's answer for more traps and pitfalls, like the "User Data Collection" form and "Archive" and "Latest releases" checkboxes.

Meteor: EJSON is not defined

I'm trying to use a private JSON file to add some simple template documents to the mongo collection if it is empty:
if (Passions.find().count() === 0) {
mockPassions = JSON.parse(Assets.getText("mockups/passions.json"));
_.each(mockPassions.passions, function(passion) {
return Passions.insert(passion);
});
}
I'm getting the error:
ReferenceError: EJSON is not defined
Does anyone have any clue? I'm using Meteor 0.6.5.
Thanks
You need to bring EJSON up to the global namespace via
meteor add ejson
In meteor 0.6.5 unless you explicitly tell it to, packages are namespaced into package
Considering Latest Meteor 1.6, you can follow below steps:
A. First Approach [Independent of the meteor restart/stop/start]
Edit .meteor/packages file and add 'ejson' to end of the file
B. Second Approach
Stop Server if already running by pressing ctrl+c
Run command meteor add ejson
Restart Server using command meteor

How can one parse HTML server-side with Meteor?

I want to be able to scrape links out of an HTML page that I am fetching with the Meteor.http method. Would be ideal to use jQuery on the server-side but I don't think this works.
Consider using cheerio its just like jquery but more for scraping. I have tried to answer this before so I hope I do a better job this time.
its an npm module so first step install it (inside your project dir) with terminal:
meteor add http
cd .meteor
npm install cheerio
So now the code:
You need to use this in your server js/or equivalent
var cheerio = __meteor_bootstrap__.require('cheerio');
Meteor.methods({
last_action: function() {
$ = cheerio.load(Meteor.http.get("https://github.com/meteor/meteor").content);
return $('.commit-title').text().trim()
}
})
If you run this from your client side js, you will see the last action on meteors github branch:
Meteor.call("last_action",function(err,result){ console.log(result) } );
I got this as of today/feb 23rd
which the same as on github.com/meteor/meteor
Use cheerio, as Akshat suggests, but I would recommend a different way of using it, as of now, for Meteor 0.8.0.
First, install npm for Meteor:
$ mrt add npm
Then modify packages.json to (of course you can have different version of cheerio, or other node packages as well):
{
"cheerio": "0.15.0"
}
In server.js (or any other file, in server-side code) start:
var cheerio = Meteor.require('cheerio');
The use cheerio in a way you like.
Upon running $ meteor it will automatically install cheerio.

Why does Meteor complain that an insert method for a collection is already defined?

Can anyone tell me why the code below throws the following error? :
Error: A method named '/players/insert' is already defined
I'm new to Meteor and coffeescript so I may be overlooking something simple.
Here's my port of the leaderboard example to coffeescript:
###
Set up a collection to contain player information. On the server,
it is backed by a MongoDB collection named "players."
###
Players = new Meteor.Collection("players")
if Meteor.is_client
Template.leaderboard.players = ->
Players.find({}, {sort: {score: -1, name: 1}})
Template.leaderboard.selected_name = ->
player = Players.findOne(Session.get "selected_player")
player and player.name
Template.player.selected = -> if Session.equals("selected_player", this._id) then "selected" else ''
Template.leaderboard.events = {
'click input.inc': ->
Players.update(Session.get("selected_player"), {$inc: {score: 5}})
}
Template.player.events = {
'click': ->
Session.set("selected_player", this._id)
}
# On server startup, create some players if the database is empty.
if Meteor.is_server
Meteor.startup ->
if Players.find().count() is 0
names = [
"Ada Lovelace"
"Grace Hopper"
"Marie Curie"
"Carl Friedrich Gauss"
"Nikola Tesla"
"Claude Shannon"
]
Players.insert({name: name, score: Math.floor(Math.random()*10)*5}) for name in names
The full stack trace is as follows:
[[[[[ ~/dev/meteor/leaderboard ]]]]]
Running on: http://localhost:3000/
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: A method named '/players/insert' is already defined
at app/packages/livedata/livedata_server.js:744:15
at Function.<anonymous> (app/packages/underscore/underscore.js:84:24)
at [object Object].methods (app/packages/livedata/livedata_server.js:742:7)
at new <anonymous> (app/packages/mongo-livedata/collection.js:111:13)
at app/leaderboard.js:4:11
at /Users/alex/dev/meteor/leaderboard/.meteor/local/build/server/server.js:109:21
at Array.forEach (native)
at Function.<anonymous> (/Users/alex/dev/meteor/leaderboard/.meteor/local/build/server/underscore.js:76:11)
at /Users/alex/dev/meteor/leaderboard/.meteor/local/build/server/server.js:95:7
Exited with code: 1
I'm running Meteor version 0.4.0 (8f4045c1b9)
Thanks in advance for assistance!
You would also get this error, regardless of using coffeescript or plain javascript, if you duplicated your files. For example, copying your sources files to a subdirectory named Backup would produce this error, because Meteor merges files from subdirectories.
This appears to be a configuration issue with coffeelint (installed globally with npm).
I originally installed coffeelint to check that my coffeescript code was correct and had no errors.
I installed coffeelint as per the instructions with:
sudo npm install -g coffeelint
coffeelint worked fine when run stand-alone against .coffee files.
However, when running any Meteor project with coffeescript package added I got the above error.
On a whim, I thought the error might be due to conflict with my exisiting node install.
I decided to uninstall coffeelint first with:
sudo npm uninstall -g coffeelint
and then deleted the previously meteor-generated leaderboard.js file.
After re-starting meteor the coffeescript example above worked as expected without errors.
try moving (ie copying and deleting the original )
Players = new Meteor.Collection("players")
one time below if Meteor.is_client
and another time below if Meteor.is_server
I don't know exactly why, as I'm new to Meteor too, but that worked for me, I assume that the server side needs it's own reference,as well as the client,
although declaring outside the scope should do the same (maybe a bug, remember they're still at 0.5.0 preview , which makes me think you might wanna upgrade and try some new smart packages that are with the new version, it looks like you're using 0.4), but when the files in my server wouldn't recognize anything I defined the root directory of meteor (which pushes these files to both client and server), I defined the server's own reference, and I got the same error, and until I moved the 'public' declaration of the reference to give the server and the client each their own copy, nothing worked.
Hopefully that helps...

Resources