Intro
This time, I will try close Microsoft Excel, Microsoft PowerPoint, and PDF(with Adobe Acrobat Reader DC) files what are opened by "child_process".
Environments
- Node.js ver.16.5.0
- TypeScript ver.4.3.5
- Powershell ver.7.1.3
- ESLint ver.7.30.0
Avoid ESlint error in webpack.config.js
After adding ESLint, I have gotten an error in webpack.config.js.
Because it uses "require".
But because it is a config file, so I want to ignore from ESLint checking in VSCode.
To do that, I added settings.json of VSCode.
- Open command palette by Ctrl + Shift + P
- Type 「Preferences」
- Click「Preferences: Open Settings (JSON)」
- add "ignorePattern"
...
"eslint.options": {
"ignorePattern": "webpack.config.js",
}
}
Close by ChildProcess.kill (Failed)
I can use "ChildProcess.kill" to stop process like below.
import { execFile } from "child_process";
export async function execute(): Promise<void> {
const execProcess = execFile('powershell', ['C:/Users/example/OneDrive/Documents/sample.pptx'], (error, stdout) => {
console.log(`execFile stdout: ${stdout} error: ${error}`);
});
setTimeout(() => {
console.log('Stop');
execProcess.kill('SIGKILL');
}, 10000);
}
But after 10 seconds, the file has still opened.
Of cource even if I change the waiting time, the result won't be changed.
Stop process
I can stop the process by a Powershell command.
Stop Excel
Stop-Process -Name EXCEL
Stop Powerpoint
Stop-Process -Name POWERPNT
Stop Acrobat
Stop-Process -Name AcroRd32
So I can close the processes by "ChildProcess.execFile".
...
setTimeout(() => {
console.log('Stop');
execFile('powershell', ['Stop-Process', '-Name', 'POWERPNT']);
}, 10000);
}
One problem is they close execution files.
Sometimes, I want to close only one pptx file, not the execution file.
Close specific files (Excel, PowerPoint)
I can close specific Excel or PowerPoint files like below.
Close Excel file
$xls = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application")
$xls.DisplayAlerts = $false
$xls.Workbooks | %{if($_.Name -imatch "sample.xlsx"){$_.Close()}}
Close PowerPoint file
$ppt = [System.Runtime.InteropServices.Marshal]::GetActiveObject("PowerPoint.Application")
$ppt.DisplayAlerts = $false
$ppt.Presentations | %{if($_.Name -imatch "sample.pptx"){$_.Close()}}
I can execute them by "ChildProcess.execFile".
But because I don't want to write them directly in Node.js code, so I create PowerShell scripts.
sample.ps1
[string]$fileName = "$args.pptx";
$ppt = [System.Runtime.InteropServices.Marshal]::GetActiveObject("PowerPoint.Application")
$ppt.DisplayAlerts = $false
$ppt.Presentations | %{if($_.Name -imatch $fileName){$_.Close()}}
I set the file name as a command-line argument.
Execute ps1 files
I can't "sample.ps1" like "./sample.ps1" on PowerShell for Security policies.
So I execute like below.
powershell -ExecutionPolicy RemoteSigned -File ./pssample.ps1 sample
Because AcroRd32.exe doesn't has close command, so maybe I shall try Acrobat SDK.
Top comments (0)