I'm trying to open files from node, If I try and open them using this code then it works
exec("excelfile.xls", {cwd: "c:\\"}, function(error, stdout, stderror){
if(error)console.log("Error: \""+stderror+"\"");
});
However, I'm trying to adapt the program to run as a service, and the only way I can get my program to open a file when it running as a service is to use spawn instead of exec:
var child = spawn("explorer.exe",[], {env: process.env, cwd: "C:\\Windows"});
child.unref();
The problem is if I try and spawn something that isn't executable then I get am ENOENT error as node doesn't know what program to use to open the file:
var child = spawn("excelfile.xls",[], {env: process.env, cwd: "c:\\"});
child.unref();
What I'm looking for is a way to extract the correct program to open a given file type from windows (and the path to that program).
I've tried using winreg to get the information from the registry, but to do that I need to lookup computer\HKEY_CLASSES_ROOT."fileExtension"\ and get the value from the "(Default)" string value, then I could look up computer\HKEY_CLASSES_ROOT\"(Default) value"\shell\Open\command\ and get the string I need to open the file.
Unfortunately, winreg doesn't appear to give you the value of the (Default) string.
var Winreg = require('winreg');
var regKey = new Winreg({
hive: Winreg.HKCR,
key : "\\.xls"
})
regKey.values(function (err, items) {
if (err)
console.log('ERROR: '+err);
else
for (var i in items){
console.log('ITEM: '+items[i].name+'\t'+items[i].type+'\t'+items[i].value);
}
});
OUTPUT
ITEM: Content Type REG_SZ application/vnd.ms-excel
EXPECTED OUTPUT
ITEM: (Default) Type REG_SZ Excel.Sheet.8
ITEM: Content Type REG_SZ application/vnd.ms-excel
So if someone could give me a way to open a non-executable file using child_process.spawn() or give me a way to extract the path to the correct program to open a file based on it's extension I'd be every so grateful.
You could try to use START command.
var child = spawn("cmd.exe", ["/c", "start", "excelfile.xls"], {env: process.env, cwd: "c:\\"});
child.unref();
My complete code:
var EventLogger = require('node-windows').EventLogger;
var log = new EventLogger('File Launcher starting');
var exec = require('child_process').exec;
var userName = "mike";
var password= "mikesPassword";
var fullPath= "C:\folder\file.xls";
exec("PSExec.exe -accepteula -h -d -u "+userName+" -p "+password+" -i 1 C:\\WINDOWS\\SYSTEM32\\CMD.EXE /c start \"\" \""+fullPath+"\"",{cwd: process.cwd}, function(error, stdout, stderror) {
if(error){
log.error(stderror.replace('\n','').replace('\r',''));
}
if(stdout){
log.info(stdout.replace('\n','').replace('\r',''));
}
});