繁体   English   中英

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

[英]Node.js: Execute server scripts via front-end

我想在我的网站on-click事件执行一些特定的node JS文件。

我正在使用express来运行我的服务器和网站。 我认为正确的方法是使用jQuery和一些GET请求。 JS文件正在工作,如果我只是在控制台中使用"node examplefile.js"调用它们

该文件如下所示:

var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
    console.log(styles);
});

我希望每次发生on-click事件时都执行此文件。

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

有关如何实现这一点的任何建议或简单示例?

创建一个新模块然后从Express应用程序调用它会好得多

创建新模块(getStyles.js):

var MapboxClient = require('mapbox');
var client = new MapboxClient('');

module.exports = function (done) {

    client.listStyles(function (err, styles) {

        if (err) {
            return done(err);
        }

        done(null, styles);
    });

}

在express app中使用它:

...

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执行命令行,那么使用exec函数,这里有一个例子:

...

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"/>

这就是我所理解的,你正在努力做到的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM