问题是,包含Unicode字符的命令会默默失败。
let childProcess = require('child_process')
let testProcess = childProcess.spawn('powershell', [])
testProcess.stdin.setEncoding('utf-8')
testProcess.stdout.on('data', (data) => {
console.log(data.toString())
})
testProcess.stdout.on('error', (error) => {
console.log(error)
})
// This path is working, I get command output in the console:
// testProcess.stdin.write("(Get-Acl 'E:/test.txt').access\n");
// This path is not working. I get nothing in the console
testProcess.stdin.write("(Get-Acl 'E:/test .txt').access\n");
编辑 #1
在将命令发送到 Powershell 并将其转换为 System.Char 之前,我已经尝试在 Node.js 端对路径进行 UTF-8 编码:
const path = 'E:/test $([char]0x1f4da).txt'
const command = `Get-Acl $(${path}).access`
testProcess.stdin.write(`${command}\n`)
但我不确定如何正确地做到这一点。看起来我没有将其编码为正确的格式。而且这也不是一个真正的解决方案,我只是手动将表情符号编码为UTF。我可能需要将整个路径转换为UTF-16或其他格式,以确保其中没有不支持的字符:
"E:/test .txt".split("").reduce((hex,c) => hex += c.charCodeAt(0).toString(16).padStart(4,"0"),"")
我不确定它是否能正常工作。