如何在Vapor中运行命令行工具以响应HTTP请求?

问题描述

我有一个node.js命令行工具,我想运行该工具来生成资产以响应在Vapor 4中收到的HTTP请求。

解决方法

我想是这样的

func requestHandler(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
    let promise = req.eventLoop.makePromise(of: HTTPStatus.self)
    let process = Process()
    // e.g. use `which node` to find path to `node`
    process.executableURL = URL(fileURLWithPath: "/path/to/binary") // e.g. /usr/bin/node
    
    // in which folder execute the command,it is optional
    process.currentDirectoryPath = "/path/to/folder"
    
    // optional arguments,e.g. if your arguments are -c release then it should be ["-c","release"]
    process.arguments = ["arg1","arg2","argN"]
    
    // wait for termination in closure
    process.terminationHandler = { process in
        switch process.terminationStatus {
        // probably normal termination via SIGTERM or when process successfully finished
        case 0:
            promise.succeed(.ok)
        default:
            promise.fail(Abort(.failedDependency,reason: "Process finished with code \(process.terminationStatus)"))
        }
    }
    
    // don't forget to launch it
    try process.run()
    
    return promise.futureResult
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...