【问题标题】:Is there a way to make CLI commands from AngularJS controller? [duplicate]有没有办法从 AngularJS 控制器发出 CLI 命令? [复制]
【发布时间】:2020-03-01 03:49:51
【问题描述】:

我创建了一个服务,使用child-process 从我的 AngularJS 控制器发出一些 CLI/终端命令,但似乎我无法做到这一点。以下是我的服务:

listFiles.js:

'use strict'
var exec = require('child_process').exec;


const listFiles = function(){
    exec('ls', (err, stdout, stderr) => {
      if (err) {
        // node couldn't execute the command
        return;
      }

      // the *entire* stdout and stderr (buffered)
      console.log('stdout: ' + stdout);
      console.log(stderr);
    });
}

export default listFiles;

我还在我的 package.json 中添加了以下内容:

"browser": { 
    "fs": false, 
    "child_process": false 
  },

我收到以下错误:

TypeError: exec 不是函数

我正在使用 webpack 来构建应用程序。有没有办法在 AngularJS 控制器/或作为 AngularJS 服务中创建 CLI 命令?

【问题讨论】:

    标签: javascript node.js angularjs webpack cmd


    【解决方案1】:

    请看下面的问题:

    Angularjs - Require('child_process')

    总结一下:您不能通过浏览器应用程序运行子进程,因为这将是一个巨大的安全问题。

    如果您想在您的服务器上运行某些命令,请使用 NodeJS 或任何其他服务器技术编写一个 REST API,然后从您的 AngularJS 应用程序中调用它。

    更新:

    这里有一个简单的例子,说明如何使用 express 处理 HTTP GET 请求。

    var express = require('express');
    var app = express();
    
    app.get('/', function (req, res) {
        const command = req.query. command // Get the command form the query parameters.
        // DO WHATEVER YOU WANT TO DO USING child_process
    
    });
    
    app.listen(3000, function () {
        console.log('App listening on port 3000');
    });
    

    你可以在官方ExpressJs documentation找到不同的例子。

    【讨论】:

    • 关于如何使用 express 编写此内容的任何见解?我有一个使用 expressjs 定义中间件的服务器。
    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多