开发者

Running stateful commands in PowerShell through Node.js

开发者 https://www.devze.com 2022-12-07 20:37 出处:网络
Context: I have a javascript file that activates PowerShell\'s native SpeechSynthesizer module. The script receives a message and passes that through to PowerShell, where it is rendered as speech.

Context: I have a javascript file that activates PowerShell's native SpeechSynthesizer module. The script receives a message and passes that through to PowerShell, where it is rendered as speech.

Problem: there is horrible latency (~5sec) between execution and response. This is because the script creates an entirely new PowerShell session and SpeechSynthesizer object with every execution.

Objective: I want to change the script so that a single PowerShell session and SpeechSynthesizer object is persisted and used across multiple sessions. I believe this will eradicate the latency completely.

Limiting Factor: this modification requires making the PowerShell execution stateful. Currently, I don't know how to incorporate stateful commands for the PowerShell in a javascript file.

Any and all suggestions are welcome. Thanks!

Code:

const path = require('path');
const Max = require('max-api');
const { exec } = require('child_process');

// This will be printed directly to the Max console
Max.post(`Loaded the ${path.basename(__filename)} script`);

const execCommand = command => {
    // Max.post(`Running command: ${command}`);
    exec(command, {'shell':'powershell.exe'}, (err, stdout, stderr) => {
        if (err) {
        // node couldn't execute the command
          Max.error(stderr);
          Max.error(err);
          return;
        }
        // the *entire* stdout and stderr (buffered)
        Max.outletBang()
      });
}

// Use the 'outlet' function开发者_运维技巧 to send messages out of node.script's outlet
Max.addHandler("speak", (msg) => {
    let add = 'Add-Type -AssemblyName System.speech'
    let create = '\$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer'
    let speak = `\$speak.Speak(\'${msg}\')`

    let command = ([include,create,selectVoice,speak]).join('; ')

    execCommand(command)
});

Objective, Re-stated: I want to move the add and create commands to a 'create' handler which will only be ran once. The speak command will be run an arbitrary amount of times afterward.

Attempted Solution: I've found one package (https://github.com/bitsofinfo/powershell-command-executor) that supposedly supports stateful PowerShell commands, but it's very complicated. Also, the author mentions a risk of command injection and other insecurities, of which I have no knowledge of.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号