2017-12-27 1314 views
2

我想執行一些特定的nodejavascript文件,在我的網站上有一個「點擊」事件。我正在使用express來運行我的服務器和網站。我認爲正確的做法是使用jQuery和一些GET請求。該Javascript文件的工作,如果我只需在控制檯"node examplefile.js"打電話給他們的文件看起來像這樣:從節點服務器執行腳本

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

我想每次執行此文件中的一個上點擊事件發生。

我是否必須將其作爲模塊導出到我的app.js?這是我想要做的,但我在實施中失敗了。

任何建議或簡單的例子如何實現這一點?

回答

0

這是更好的創建一個新的模塊,然後由快遞應用

稱之爲創建新的模塊(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); 
    }); 

} 

使用它明確內部應用程序:

... 

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

}); 

... 
0

1.Write功能在您examplefile.js

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

2.Include examplefile.js在app.js

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

3.Then調用()由的onclick(從app.js)事件文件

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

這是我的理解,你正在嘗試做的。

相關問題