您可以使用node ddp package 在您使用特定脚本创建的自己的 js 文件中调用 Meteor 方法。从那里您可以将所有输出通过管道传输到您想要的任何地方。
让我们假设以下 Meteor 方法:
Meteor.methods({
'myMethod'() {
console.log("hello console")
return "hello result"
}
})
假设您的 Meteor 应用程序正在运行,接下来的步骤将允许您从另一个 shell 调用此方法。
1.在全局 npm 目录中安装 ddp
$ meteor npm install -g ddp
2。创建脚本以在您的测试目录中调用您的方法
$ mkdir -p ddptest
$ cd ddptest
$ touch ddptest.js
使用您选择的编辑器或命令将 ddp 脚本代码放入文件中。
(以下代码是从包的自述文件中免费获取的。请根据您的需要随意配置。)
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);
});
代码假定您的应用程序在localhost:3000 上运行,请注意没有关闭错误或不良行为的连接。
正如您在顶部看到的,该文件会导入您全局安装的 ddp 包。现在为了在不使用其他工具的情况下获取它的路径,只需传递一个环境变量 (process.env.DDP_PATH) 并让您的 shell 处理路径解析。
为了获得安装路径,您可以使用带有全局标志的npm root。
最后通过以下方式调用您的脚本:
$ DDP_PATH=$(meteor npm root -g)/ddp meteor node ddptest.js
这将为您提供以下输出:
connected!
updated
undefined
called function, result: hello result
并将hello console 记录到正在运行您的流星应用程序的打开会话中。
编辑:关于在生产中使用它的说明
如果您想在生产中使用此脚本,您必须使用不带meteor 命令的shell 命令,而是使用您安装的node 和npm。
如果您遇到路径问题,请使用 process.execPath 查找您的节点二进制文件并使用 npm root -g 查找您的全局 npm 模块。