在后台模式下从Nodejs执行VBS(任务调度程序或Windows服务)



我正在尝试从NodeJS应用程序将Excel文件转换为PDF。当我在命令行中启动Node时,它可以工作,但当我通过NSSM或直接使用Tasks Scheduler将app.bat作为Windows服务启动时,它就不再工作了。

使用下面的脚本,我只能看到log.txt中的第一行,即程序参数。如果一切顺利,我应该看到0,然后是1和2。遗憾的是,当Node在后台运行时,我没有任何数字,所以我猜问题是CreateObject("Excel.Application"),但我不知道为什么以及如何解决它。

VBScript:

Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile="C:UsersadminDocumentsProjectstoolslog.txt"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write Wscript.Arguments.Item(0) & " | " & WScript.Arguments.Item(1) & vbCrLf
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
objFile.Write "0" & vbCrLf
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
objFile.Write "1" & vbCrLf
oBook.ExportAsFixedFormat xlTypePDF, WScript.Arguments.Item(1)
objFile.Write "2" & vbCrLf
oBook.Close True

NodeJS:

const {exec} = require('child_process');
exec('"' + Meteor.settings.directories.tools + 'convertToPDF.vbs" "' + outputServerFilePathChild + '.xlsx" "' + outputServerFilePathChild + '.pdf"', (err, stdout, stderr) => {
if (err) {
console.log(stderr);
reject(new Error(stderr));
} else {
if (fs.existsSync(outputServerFilePathChild.replace(/ /g, "%20") + ".pdf")) {
console.log('rename "' + outputServerFilePathChild.replace(/ /g, "%20") + '.pdf" "' + outputServerFilePathChild + '.pdf"');
exec('rename "' + outputServerFilePathChild.replace(/ /g, "%20") + '.pdf" "' + outputServerFilePathChild + '.pdf"', (err, stdout, stderr) => {
console.log("File generated: " + outputServerFilePathChild + ".pdf");
resolve(outputClientFilePathChild + ".pdf");
});
} else {
console.log("File generated: " + outputServerFilePathChild + ".pdf");
resolve(outputClientFilePathChild + ".pdf");
}
}
});

我也尝试过这样的东西:

const child2 = spawn('start', [
'"PDFConverter"',
'cscript',
'"C:\Users\admin\Documents\Projects\tools\convertToPDF.vbs"',
'"C:\Users\admin\Documents\Projects\reports\admin\rebates\customer1 2019-09-30.xlsx"',
'"C:\Users\admin\Documents\Projects\reports\admin\rebates\customer1 2019-09-30.pdf"'
], {
shell: true,
windowsHide: true,
});

然而,它也不起作用。有人有主意吗?

编辑:这个问题似乎无法解决。许多年前,有些人也提出过同样的问题,但至今没有答案。。。

  • Node.js作为服务,exec不';t工作

  • nodejs服务-在windows系统中,无法执行jar文件

我找到了答案(但这并不是真正的解决方案(。正如我所猜测的,这个问题与Excel有关,所以它不是VBScriptNodeJS。我在C#中使用EdgeJs做了同样的事情,我也遇到了同样的问题。

您可以编辑/创建带有库的Open XML文件,但不能保存为PDF或在服务器模式下使用任何宏。

微软的答案:

https://support.microsoft.com/en-us/help/257757/considerations-for-server-side-automation-of-office?wa=wsignin1.0%3Fwa%3Dwsignin1.0

如果使用服务器端解决方案中的Office应用程序应用程序将缺乏运行所需的许多功能成功地

CreateObject函数和CoCreateInstance函数返回一个的运行时错误消息,并且无法为启动自动化……

我也尝试过使用winax(使用节点ffi的节点插件(,结果相同。它可以在客户端模式下工作,但不能在服务器模式下工作(DispInvoke:Open Microsoft Excel无法访问文件(。

最新更新