[英]Node.js: Execute server scripts via front-end
I'd like to execute some specific node
JS
files with an on-click
event at my Website. 我想在我的网站on-click
事件执行一些特定的node
JS
文件。
I'm using express
to run my server and website. 我正在使用express
来运行我的服务器和网站。 I think the right way to do this is using jQuery
with some GET
requests. 我认为正确的方法是使用jQuery
和一些GET
请求。 The JS files are working, if i call them simply in the console with "node examplefile.js"
JS文件正在工作,如果我只是在控制台中使用"node examplefile.js"
调用它们
The file looks like this: 该文件如下所示:
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
I want to execute this file everytime an on-click
event occurs. 我希望每次发生on-click
事件时都执行此文件。
Do I have to export this as a module to my app.js
? 我是否必须将此模块作为模块导出到我的app.js
? This is what I wanted to do, but I failed in the implementation. 这就是我想要做的,但我在实施中失败了。
Any suggestions or simple examples on how to realize this? 有关如何实现这一点的任何建议或简单示例?
It's much better to create a new module and then call it from express app 创建一个新模块然后从Express应用程序调用它会好得多
create new module (getStyles.js): 创建新模块(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);
});
}
Use it inside express app: 在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)
});
});
...
However if you want to execute a command line from express, then use exec function, here is an example: 但是如果你想从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.Write your examplefile.js within a function 1.在函数中编写examplefile.js
function a(){
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
2.Include examplefile.js in your app.js 2.在app.js中包含examplefile.js
<script src="examplefile.js" type="text/javascript"></script>
3.Then call a() by onclick() event from your app.js file 3.然后通过app.js文件中的onclick()事件调用()
<input type="button" onclick="javascript: a();" value="button"/>
That is what i understood, you are trying to do. 这就是我所理解的,你正在努力做到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.