Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Node.js:通过前端执行服务器脚本_Javascript_Jquery_Html_Node.js_Express - Fatal编程技术网

Javascript Node.js:通过前端执行服务器脚本

Javascript Node.js:通过前端执行服务器脚本,javascript,jquery,html,node.js,express,Javascript,Jquery,Html,Node.js,Express,我想在我的网站上执行一些特定的节点JS文件,其中包含一个点击事件 我正在使用express运行我的服务器和网站。我认为正确的方法是使用jQuery和一些GET请求。如果我在控制台中使用“node examplefile.JS” 该文件如下所示: var MapboxClient = require('mapbox'); var client = new MapboxClient(''); client.listStyles(function (err, styles) { console

我想在我的网站上执行一些特定的
节点
JS
文件,其中包含一个
点击事件

我正在使用
express
运行我的服务器和网站。我认为正确的方法是使用
jQuery
和一些
GET
请求。如果我在控制台中使用
“node examplefile.JS”

该文件如下所示:

var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
    console.log(styles);
});
我想在每次单击
事件发生时执行此文件

我是否必须将其作为模块导出到我的
app.js
?这是我想要做的,但我在实现中失败了


关于如何实现这一点,有什么建议或简单的例子吗?

最好创建一个新模块,然后从express app调用它

创建新模块(getStyles.js):

在express应用程序中使用它:

...

var getStyles = new MapboxClient('path/to/getStyles');

app.get( '/your/route/here', function (req, res, next) {

    getStyles( function (err, styles) {

        if (err) return next(err);

        res.render('view', styles)

    });

});

...
但是,如果要从express执行命令行,请使用函数,下面是一个示例:

...

const exec = require('child_process').exec;

app.get( '/on/click/buton/route', function (req, res, next) {

    exec('/usr/bin/node file/path/.js', function (err, stdout, stderr) {
        if (err) {
            return next(err);
        }
        // send result to the view
        res.render('veiw', { res:  stdout});
    });

});

...

1.在函数中编写examplefile.js

function a(){
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
2.在app.js中包含examplefile.js

<script src="examplefile.js" type="text/javascript"></script>

3.然后从app.js文件中通过onclick()事件调用()

<input type="button" onclick="javascript: a();" value="button"/>

这就是我所理解的,你正试图这么做

<input type="button" onclick="javascript: a();" value="button"/>