【问题标题】:Node.js: Execute server scripts via front-endNode.js:通过前端执行服务器脚本
【发布时间】:2018-06-08 09:32:58
【问题描述】:

我想在我的网站上执行一些带有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 吗?这是我想做的,但我在实施中失败了。

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

【问题讨论】:

    标签: javascript jquery html node.js express


    【解决方案1】:

    创建一个新模块,然后从 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 应用中使用它:

    ...
    
    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});
        });
    
    });
    
    ...
    

    【讨论】:

      【解决方案2】:

      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() 事件调用 a()

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

      这就是我的理解,你正在尝试做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多