【发布时间】:2018-02-03 23:02:36
【问题描述】:
我的问题的标题是如何从 node.js 应用程序运行命令行工具,因为我认为这里的答案将适用于可从 npm 安装的所有命令行实用程序。我已经看到与从 node.js 运行命令行相关的问题,但它们似乎不适用于我的情况。具体来说,我正在尝试运行一个类似于 npm 的节点命令行实用程序(在它的使用方式上,但不是它的功能),称为 tilemantle。
tilemantle 的 documentation 显示全局安装 tilemantle 并从命令行运行程序。
我想做的是使用 npm install tilemantle --save 在本地安装 tilemantle 作为 npm 项目的一部分,然后从我的项目内部运行 tilemantle。
我尝试了`tilemantle = require('tilemantle'),但是tilemantle项目中的index.js文件是空的,所以我认为这没有任何帮助。
我尝试了node-cmd的项目
const cmd = require('node-cmd');
cmd.run('./node_modules/tilemantle/bin/tilemantle', 'http://localhost:5000/layer/{z}/{x}/{y}/tile.png', '-z 0-11', '--delay=100ms', '--point=37.819895,-122.478674', '--buffer=100mi'
这不会引发任何错误,但它也不起作用。
我也尝试过子进程
const child_process = require('child_process');
child_process.exec('./node_modules/tilemantle/bin/tilemantle', 'http://localhost:5000/layer/{z}/{x}/{y}/tile.png, -z 0-11 --delay=100ms --point=37.819895,-122.478674 --buffer=100mi'
这也不会引发任何错误,但它也不起作用。
有没有办法让它工作,这样我就可以从我的程序内部运行 tilemantle 而无需全局安装它?
更新
我可以使用 tilemantle 从我的终端运行
node './node_modules/tilemantle/bin/tilemantle', 'http://localhost:5000/layer/{z}/{x}/{y}/tile.png', '--delay=100ms', '--point=37.819895,-122.478674', '--buffer=100mi', '-z 0-11'
如果我按照jkwok 的建议运行以下命令
child_process.spawn('tilemantle', ['http://myhost.com/{z}/{x}/{y}.png',
'--point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'],
{ stdio: 'inherit' });
我得到spawn tilemantle ENOENT,如果我用./node_modules/tilemantle/bin/tilemantle.js 替换tilemantle,我得到spawn UNKNOWN
基于jfriend00's answer,听起来我实际上需要生成节点,所以我尝试了以下方法
child_process.spawn('node', ['./node_modules/tilemantle/bin/tilemantle.js', 'http://myhost.com/{z}/{x}/{y}.png', '--point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'], { stdio: 'inherit' });
这给了我错误spawn node ENOENT 这似乎很奇怪,因为我可以从我的终端运行它,我检查了我的路径变量并且C:\Program Files\nodejs 在我的路径上。
只是为了检查我尝试使用节点的完整路径运行以下命令。
child_process.spawn('c:/program files/nodejs/node.exe', ['./node_modules/tilemantle/bin/tilemantle.js', 'http://myhost.com/{z}/{x}/{y}.png', '--point=44.523333,-109.057222', '--buffer=12mi', '-z', '10-14'], { stdio: 'inherit' });
它在没有 ENOENT 错误的情况下运行,但它再次静默失败,只是没有预热我的磁贴服务器。
我正在使用 Node 6.11.0 运行 Windows 10 x64
【问题讨论】:
-
我链接的帖子有一条关于在 Windows 上运行的评论here
标签: javascript node.js npm