Node.JS EXE Deleting executing file - node.js

I have an monitor.js file that I turned into an executable using nexe.
I want the monitor to have the ability to uninstall itself, which means delete it's own .exe file and his containing directory.
I tried : (monitorPath = monitor.exe file path, installPath = monitor.exe folder)
childProcess.exec("TIMEOUT 3 && del " + monitorPath + " && rmdir " + installPath);
setTimeout(function() {
process.exit(0);
}, 2000);
EDIT: It should run on windows, so those are all windows commands

Solved using the start command
var installPath = path.join(exePath, "..");
var monitorPath = path.join(installPath, "qqmonitor.exe");
var delCommand = 'start cmd /c "cd .. && TIMEOUT 1 && del "' + monitorPath + '" && rmdir "' + installPath + '" && exit"';
log("Uninstalling with command : '" + delCommand + "'");
childProcess.exec(delCommand, null);
setTimeout(function () {
process.exit(0);
}, 500);

Related

exec format error at system.diagnostics.process

I have a .net core application which will unzip a file using 7zip.exe. this application is working fine with windows. once after I deployed it in docker , I am getting an error as "exec format error at system.diagnostics.process".
var processStartInfo = new ProcessStartInfo
{
FileName = sevenZPath,
Arguments = "x \"" + filePath + Path.DirectorySeparatorChar + fileName + "\" -o" + outputPath
};
var process = System.Diagnostics.Process.Start(processStartInfo);
process?.WaitForExit();
Even if I am running the exe directly from the container I am getting the same error.

How to do Mongodb Backup with node js

I am wirting a mongodb auto backup code but i am stuck in some error: 'mongodump' is not recognized as an internal or external command.
can anyone help me out?
or is there another way to get auto backup with mongodb
exports.dbAutoBackUp = () => {
let cmd =
'mongodump --host ' +
dbOptions.host +
' --port ' +
dbOptions.port +
' --db ' +
dbOptions.database +
' --username ' +
dbOptions.user +
' --password ' +
dbOptions.pass +
' --out ' +
newBackupPath;
exec(cmd, (error, stdout, stderr) => {
console.log("Error : "+error)
console.log("Error 1: "+stdout)
console.log("Error 2: "+stderr)
if (this.empty(error)) {
// check for remove old backup after keeping # of days given in configuration.
if (dbOptions.removeOldBackup == true) {
if (fs.existsSync(oldBackupPath)) {
exec('rm -rf ' + oldBackupPath, err => {
console.log(err);
});
}
}
}
});
}
};
The error is probably because you are not in the directory where you have mongodb executable.
There are two ways to do it.
change your directory to mongodb's installation path
Add the mongodb executable to your environment variables
Path should be something like
{installation_directory}:\Program Files\MongoDB\Server\{version}\bin
For example
C:\Program Files\MongoDB\Server\4.2\bin

Run cmd commands in JScript

I have a cmd command which I need to execute in JScript. So, I'm trying the next sequence of code:
var WshShell = new ActiveXObject("WScript.Shell");
sevenZip = "C:\\Program Files\\7-Zip\\7z.exe";
WshShell.Run("cmd.exe /c '"+sevenZip+" e "+File+" -p"+Pass+"'");
But when I launch the script, the cmd window opens, then closes, but the command doesn't seem to be executed. What am I doing Wrong?
I'd recommend using Shell.Aplication instead. Here's the code how it should look like :
var objShell = new ActiveXObject("Shell.Application");
sevenZip = "C:\\Program Files\\7-Zip\\7z.exe";
executableCommand = "x " + zipFile + " -p" + zipPass + " -o" + Temp;
objShell.ShellExecute("7z.exe", executableCommand, sevenZip , "open", 0);
chcp 1251,866 - change it to your regional parameters
var htmlfile=new ActiveXObject('htmlfile').parentWindow;
var alert=function(s){htmlfile.alert(s)};
var echoIt='Hi'
//...solve the problem of doubling percentages in variables during transmission by introducing the parameter /v!
var cmdCode=[
'for /F "tokens=1-6 delims=:., " %A In ("!date! !time!") Do (Echo %A.%B.%C %D:%E:%F)',
'set var='+echoIt,
'echo %var%',
'echo !var!'
];//'setlocal disableDelayedExpansion' parameter is useless becose /v
var std, arr=[];
var WshRunning=0,WshFinished=1,WshFailed=2;var i=0;tryCount=0,output=[],errors=[];
with (new ActiveXObject('WScript.Shell')) {
std=Exec("cmd /v /q /k echo off"); //Turning on the /v option last, switches the output here in its entirety, including C:\...\notepad>
std.StdIn.WriteLine("chcp 1251>nul");
for(var i=0;i<cmdCode.length;i++) {
std.StdIn.WriteLine(cmdCode[i]);
};
std.StdIn.WriteLine("chcp 866>nul");
std.StdIn.WriteLine("exit");
do{
if (std.Status==WshFailed){
errors.push('Error in string '+i+' :\n '+std.StdErr.ReadLine());
tryCount++
}
else if(std.Status==WshRunning){
output.push(std.StdOut.ReadLine());
tryCount=0;
WScript.Echo('Running ...')
}
else if(std.Status==WshFinished){
var last=std.StdOut.ReadLine();
if(last.length>0){output.push(last)};last=undefined;
tryCount=21;
WScript.Echo('Finished ...')
}i++;
}while(tryCount<21);
}
WScript.Echo('')
if (output.length>0){for(var i=0;i<output.length;i++) {WScript.Echo(output[i])}}
if (errors.length>0){alert(errors)}
var x=WScript.StdIn.ReadLine();
or
var std, arr = [];
var oWsh = new ActiveXObject("WScript.Shell");
with (new ActiveXObject('WScript.Shell')) {
std = Exec("cmd /q /k chcp 1251>nul");
with (std.StdIn){
WriteLine("dir "+ oWsh.SpecialFolders("Desktop"));
WriteLine("exit");
}
arr = std.StdOut.ReadAll().split('\n'); //чтение данных
}
for (var i = 0; i < arr.length; i++) {
WScript.echo(i+' '+arr[i]);
}
var x = WScript.StdIn.ReadLine();

Phonegap barcode prompts to enter value

Am using phonegap-plugin-barcodescanner in a phonegap app to scan QR codes.
When firing the scanner using:
function scan() {
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
The camera doesn't start - I just get a prompt saying:
"Enter barcode value (empty value will fire handler)"
Any ideas welcome TQ
The prompt says "Enter barcode value (empty value will fire handler)" maybe because you run platform browser. I' ve got the same "problem" when i run my project with "cordova run browser", and "browser" is a platform installed.

How can I get msysgit on windows to invoke node.js scripts in hooks?

I would like to use node.js scripts as my git hook scripts. Currently I'm experimenting on my Windows machine with Bonobo Git HTTP service which is attached to msysgit Git-1.9.0-preview20140217 portable installation. It works fine, tested with copuple pulls and pushes.
I have nodejs up and running but my git update script just fails without any clear reason. It definitely works - it started to always reject pushes as soon as I added it into the hooks folder on the server but there are no any clues in SourceTree output log.
Here is my update script:
#!C:/nodejs/node.exe
console.log('Hello world!');
console.log('Hello world 2!');
I tried back slashes, I tried double forward slashes, I tried quoting the path - no results.
Server response is as follows:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags origin master:master
Pushing to http://myurl.git
POST git-receive-pack (4686 bytes)
remote: error: hook declined to update refs/heads/master[K
To http://myurl.git
! [remote rejected] master -> master (hook declined)
error: failed to push some refs to 'http://myurl.git'
Completed with errors, see above.
P.S. I don't know where [K comes from, my gusess is that it's corrupted newline character.
I ended up using similar approach to the one I found someone was using for Python.
I created a C# console app as follows:
using System;
using System.Diagnostics;
using System.IO;
namespace GitNodeRunner
{
class Program
{
static int Main(string[] args)
{
if (args == null || args.Length == 0)
{
Console.Error.WriteLine("Path to script file not specified");
return -1;
}
string argString = string.Join(" ", args);
Console.WriteLine("Node.js arguments received: {0}", argString);
string nodePath = Environment.GetEnvironmentVariable("NODE_HOME",
EnvironmentVariableTarget.Machine); // without "Machine" Git's Bash loses it
if (string.IsNullOrWhiteSpace(nodePath))
{
Console.Error.WriteLine("NODE_HOME global envirnoment variable not found");
return -1;
}
nodePath = Path.Combine(nodePath, "node.exe");
ProcessStartInfo start = new ProcessStartInfo
{
UseShellExecute = false,
Arguments = argString,
FileName = nodePath,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Process process = new Process();
process.StartInfo = start;
process.EnableRaisingEvents = true;
process.OutputDataReceived += process_OutputDataReceived;
process.ErrorDataReceived += process_OutputDataReceived;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
return process.ExitCode;
}
static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string s = e.Data;
Console.Out.WriteLine(s);
}
static void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
string s = e.Data;
Console.Error.WriteLine(s);
}
}
}
I compiled it as git-nodejs.exe, put into Git's bin folder, ensured that I have NODE_HOME environment variable defined, and now I can use node.js scripts. As an example, I provide my node.js update hook which rejects pushes with malformed comment messages:
#!/bin/git-nodejs
// bin/git-nodejs is our custom C# programmed node launcher
// the following code is ported from http://git-scm.com/book/en/Customizing-Git-An-Example-Git-Enforced-Policy
// we have some offset from standard Git args here:
// 0 is path to node
// 1 is path to this script
var exec = require('child_process').exec,
refname = process.argv[2],
oldrev = process.argv[3],
newrev = process.argv[4],
regexMatch = /^REF #\d* /; // in my case I require strict start with "REF #number "
console.log("Enforcing policies in branch " + refname + " for commits between revisions " + oldrev + " and " + newrev);
// we have a special case - if this is a new branch, oldrev..newrev will cause git to throw an error,
// that's why we check for empty branch commit ID
var revListCmd = (oldrev === "0000000000000000000000000000000000000000") ?
"git rev-list " + newrev + " --not --branches=*" :
"git rev-list " + oldrev + ".." + newrev;
exec(revListCmd,
function (error, stdout, stderr) {
if (error !== null) {
console.error("Exec error: " + error);
exitError();
}
var missedRevs = stdout.split("\n");
missedRevs.forEach(function(rev){
// there is a redundant empty entry at the end after split()
if (rev.length === 0) {
return;
}
console.log("Verifying policy for revision " + rev);
// | sed '1,/^$/d' does not quite work as expected on Windows
// - it returns all commit details instead of comment
// thus we complete the processing from JavaScript
exec("git cat-file commit " + rev,
function (error, stdout, stderr) {
if (error !== null) {
console.error("Exec error: " + error);
exitError();
}
// we skip the blank line (two sequential newlines) and take everything that follows
// not sure if this is the best solution but "it works on my machine"
var commitMessage = stdout.split("\n\n")[1];
// notice: if commit message missing, git will report it as "no message"
if (commitMessage.match(regexMatch) === null) {
console.error("Commit message '" + commitMessage + "' does not match the required pattern " + regexMatch);
exitError();
}
});
});
});
//////////////////////////
// some helpers
function exitError()
{
// hack for bug https://github.com/joyent/node/issues/3584
// delay exit until stdout on Windows has had some time to flush
setTimeout(function() {
console.error("Exiting with error status 1");
process.exit(1);
}, 1000);
}

Resources