Execute bat file with electron - node.js

Hello I'm creating an app with react and electron and I have a weird bug. My app have to execute a bat file so I use exec to launch the bat file with paramters like this
import { homedir } from 'os';
import * as path from 'path';
import { access, mkdir } from 'fs/promises';
import { promisify } from 'util';
import * as childProcess from 'child_process';
const exec = promisify(childProcess.exec);
const newProject = async (event: any, ...args: string[]): Promise<any> => {
const home = homedir();
const dir = path.join(home, '/work', args[0]);
// create project directory
try {
await access(dir);
return { ok: false, err: 'project already exist' };
} catch (e) {
await mkdir(dir, { recursive: true });
}
const scripts = path.join(__dirname, 'new-project.bat');
// C:\Users\Isai\Documents\work\hercule\apollon\electron\handlers\new-project.bat
try {
await exec(`${scripts} ${dir} ${args[1]}`);
return { ok: true, msg: 'folder successfully created' };
} catch (e) {
console.log(e);
return { ok: true, err: "unable to create project's folder" };
}
};
export default newProject;
when I do like this I get an error who said that it is not an internal or external command but if I mannualy enter the path of the bat file it work. So I replace the line :
await exec(`${scripts} ${dir} ${args[1]}`);
by
await exec(`C:\Users\Isai\Documents\work\hercule\apollon\electron\handlers\new-project.bat ${dir} ${args[1]}`);
It work perfectly. At the beginning I though I had the wrong path but they are the same. So I don't understant why it's doing that and I can't enter manually the path or it won't work on other machine
EDIT: I have forget to tell that a piece of the script is correctly executing because it create the folder at the good place but I get an error
Here is my bat file
#echo off
cd %1
git init
git checkout -b main
echo This project was created with Hercule>> readme.md
git add .
git commit -m "init commit"
git remote add origin %2
git push -u origin main
Here is the error
Error: Command failed: C:\Users\Isai\Documents\work\hercule\apollon\build\electron\handlers\new-project.bat C:\Users\Isai\work\return-of-the-patato https://github.com/Eexy/return-of-the-patato.git
[2] 'C:\Users\Isai\Documents\work\hercule\apollon\build\electron\handlers\new-project.bat' n'est pas reconnu en tant que commande interne
[2] ou externe, un programme ex�cutable ou un fichier de commandes.
[2]
[2] at ChildProcess.exithandler (child_process.js:317:12)
[2] at ChildProcess.emit (events.js:315:20)
[2] at maybeClose (internal/child_process.js:1048:16)
[2] at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5) {
[2] killed: false,
[2] code: 1,
[2] signal: null,
[2] cmd: 'C:\\Users\\Isai\\Documents\\work\\hercule\\apollon\\build\\electron\\handlers\\new-project.bat C:\\Users\\Isai\\work\\return-of-the-patato https://github.com/Eexy/return-of-the-patato.git',
[2] stdout: '',
[2] stderr: "'C:\\Users\\Isai\\Documents\\work\\hercule\\apollon\\build\\electron\\handlers\\new-project.bat' n'est pas reconnu en tant que commande interne\r\n" +
[2] 'ou externe, un programme executable ou un fichier de commandes.\r\n'
[2] }
It is in french but it said that it is not a internal command

I have found the probrem when I compile for electron __dirname is equal to " C:\Users\Isai\Documents\work\hercule\apollon\build\electron\handlers\new-project.bat" and I didn't see the build folder which is explain why I was having a issue

Related

Switching Storybook from Webpack to Vita in Gatsby app

I work on a Gatsby project and I'm hoping to run our Storybook with Vita instead of our existing Webpack setup. I'm clearly not doing it right.
I added the plugins:
"#storybook/builder-vite": "^0.4.2",
"#vitejs/plugin-react": "^3.1.0",
"vite": "^4.1.1",
I also added our aliases by importing my tsconfigand converting the paths to the right format.
Although most of my attempts to run it resulted in about 1000 instances of
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
it's actually running now. And it booted up WAY faster than it used to.
The only issue appears to be that it's not reloading, not at all. I make a change in a component, or a change in a story, and there is zero output in the terminal running storybook.
Although I do notice that this run, although it looks like it's working in the browser, does still give only these two errors:
Failed to resolve dependency: react/jsx-runtime, present in 'optimizeDeps.include'
Failed to resolve dependency: react/jsx-dev-runtime, present in 'optimizeDeps.include'
How can I fix this? I'm so close!
I've tried...
const react = require('#vitejs/plugin-react');
//...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
// is this where this goes?
plugins: [
react({
jsxRuntime: 'classic',
}),
],
resolve: { alias: aliasPathsVite },
},
})
},
}
Which does open Storybook in the browser, but it doesn't load, and the terminal gives endless instances of:
10:30:38 AM [vite] Internal server error: Transform failed with 2 errors:
Typography/Links.tsx:3:4: ERROR: The symbol "prevRefreshReg" has already been declared
Typography/Links.tsx:4:4: ERROR: The symbol "prevRefreshSig" has already been declared
Plugin: vite:esbuild
File: Typography/Links.tsx:1:42
The symbol "prevRefreshReg" has already been declared
1 | import RefreshRuntime from "/#react-refresh";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) { if (!window.__vite_plugin_react_preamble_installed__) { throw new Error( "#vitejs/plugin-react can't detect preamble. Something is wrong. " + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" ); } prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = (type, id) => { RefreshRuntime.register(type, "Typography/Links.tsx" + " " + id) }; window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}var _jsxFileName = "Typography/Links.tsx";
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
| ^
4 | let prevRefreshSig;
5 | if (import.meta.hot) {
The symbol "prevRefreshSig" has already been declared
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
4 | let prevRefreshSig;
| ^
5 | if (import.meta.hot) {
6 | if (!window.__vite_plugin_react_preamble_installed__) {
at failureErrorWithLog (node_modules/esbuild/lib/main.js:1604:15)
at node_modules/esbuild/lib/main.js:837:29
at responseCallbacks.<computed> (node_modules/esbuild/lib/main.js:701:9)
at handleIncomingPacket (node_modules/esbuild/lib/main.js:756:9)
at Socket.readFromStdout (node_modules/esbuild/lib/main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)
I've tried...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
resolve: {
alias: {
...aliasPathsVite,
'react/jsx-runtime': path.join(
__dirname,
'node-modules/react/jsx-runtime'
),
},
optimizeDeps: {
include: ['react/jsx-runtime']
}
},
})
},
}
which opens a non-working Storybook in the browser, and the terminal says this hundreds of times
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
Then some of these:
[vite] error while updating dependencies:
Error: ENOENT: no such file or directory, rename 'node_modules/.vite-storybook/deps_temp' -> 'node_modules/.vite-storybook/deps'
at renameSync (node:fs:1030:3)
at Object.commit (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42874:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async commitProcessing (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42348:17)
at async runOptimizer (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42386:17)
And then a bunch of issues importing CSS files, like this one
10:45:29 AM [vite] Internal server error: Failed to resolve import "./header.css" from "node_modules/#storybook/mdx1-csf/dist/esm/stories/Header.js?v=ec48b265". Does the file exist?
Have you tried something like this?
resolve: {
alias: {
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
Source: https://github.com/vitejs/vite/issues/6215
Also:
optimizeDeps.include: ['react/jsx-runtime']
Another way can be tweaking the configuration of #vitejs/plugin-react:
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
jsxRuntime: 'classic',
}),
]
});

execSync throws and error trying to run node

I am running some processes inside of an EC2 instance.
To run it I initiate it with an SSM command:
cd / && cd home/ec2-user && . .nvm/nvm.sh && cd ufo && npm run start
and inside of it, I have a method in app.ts which is initialized with ts-node app.ts
import { execSync } from 'node:child_process';
import { takeNextScheduledAudit } from './sqs-scheduler';
import { uploadResultsToBucket } from './s3-uploader';
import { AuditRunParams } from "./types";
import { sendAuditResults } from "./sendResults";
(async function conductor(): Promise<void> {
const nextAuditRunParams = await takeNextScheduledAudit();
if (!nextAuditRunParams) {
execSync("sudo shutdown -h now");
}
const { targetUrl, requesterId, endpoint } = nextAuditRunParams as AuditRunParams;
try {
execSync(`npx user-flow --url=${targetUrl} --open=false`);
const resultsUrl = await uploadResultsToBucket(targetUrl);
await sendAuditResults(requesterId, endpoint, resultsUrl);
} catch (error) {
console.log(error);
}
await conductor();
})();
If I log in manually and run npm run start the scripts works as intended but if I run it using the SSM command I get this output:
> start
> ts-node app.ts
Error: Command failed: npx user-flow --url=https://deep-blue.io/ --open=false
at checkExecSyncError (node:child_process:841:11)
at execSync (node:child_process:912:15)
at conductor (/home/ec2-user/ufo/app.ts:15:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
status: 243,
signal: null,
output: [ null, <Buffer >, <Buffer 0a> ],
pid: 2691,
stdout: <Buffer >,
stderr: <Buffer 0a>
}
and this error:
Error: Command failed: sudo shutdown -h now
at checkExecSyncError (node:child_process:841:11)
at execSync (node:child_process:912:15)
at conductor (/home/ec2-user/ufo/app.ts:10:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async conductor (/home/ec2-user/ufo/app.ts:21:5) {
status: null,
signal: 'SIGTERM',
output: [ null, Buffer(0) [Uint8Array] [], Buffer(0) [Uint8Array] [] ],
pid: 2705,
stdout: Buffer(0) [Uint8Array] [],
stderr: Buffer(0) [Uint8Array] []
}
failed to run commands: exit status 1
Moreover, if I run execSync("node -v && npx -v") it also throws an error.
Why can I run this script when i am logged in but if i run it via a SSM command it does not recognize node inside of node?
--- Edit - Added Info ---
When running execSync(node -v && npx -v,{shell: '/bin/bash'}) I get an error:
Error: Command failed: node -v && npx -v
When running execSync(ps -p $$ && echo $SHELL, {shell: '/bin/bash'}):
PID TTY TIME CMD
7817 ? 00:00:00 bash
/bin/bash
And when I loggin and do ps -p $$ && echo $SHELL I get:
PID TTY TIME CMD
6873 pts/0 00:00:00 bash
/bin/bash
By default, all of the child_process functions execute in the same environment as the process that launched them. I don't have an account handy to test with, but it's quite likely that SSM skips over a traditional shell and just executes certain runtimes directly.
You can use the exec options like this to set a particular shell in which to launch the process:
const output = execSync('echo "doing stuff"', {
shell: '/bin/bash',
})
console.log('***** output:', output.toString())
This is assuming the OS you're using for the EC2 instance has bash available. Most flavors of linux should, but for what you're doing there, /bin/sh is sufficient if not. To get a list of the available shells, you can run:
cat /etc/shells
## or possibly
sudo cat /etc/shells
EDIT: Since you say it works fine in a shell already, you have presumably already handled this, but user-flow would also have to be available. It's not a module from npmjs, so would need to already be present on the box as either a local dependency or a private repo to which the EC2 instance has access.

Is There a way to get the full path of file dependencies in Madge API?

I'm using Magde API (https://github.com/pahen/madge/blob/master/README.md) to generate the dependency graph of my JS file...
Once the dependencies are return as object, the file paths are not clearly documented... I was wondering if there exists a way to tell Madge to specify the full path not the cut it
I want to get the dependencies of this file:
import * as t from 'C:/Users/Tec/todolist_example_jest/req2.js';
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
As we can see there exists a dependency on this file:
'C:/Users/Tec/todolist_example_jest/req2.js'; But when using madge to get the dependencies ... look below to see what is the output
Here is the code snippet:
madge('file path').then((res) => {
dependencies = res.obj(); // the dependencies as an object
console.log(dependencies);
});
and this is the output:
{
'../../../../todolist_example_jest/req2.js': [],
'simpleElement.jsx': [ '../../../../todolist_example_jest/req2.js' ]
}
../../../../todolist_example_jest/req2.js
node:fs:585
handleErrorFromBinding(ctx);
^
Error: ENOENT: no such file or directory, open '../../../../todolist_example_jest/req2.js'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at C:\Users\Tec\React Native Applications\Upload-main\backend\app.js:47:27
at Array.forEach (<anonymous>)
at C:\Users\Tec\React Native Applications\Upload-main\backend\app.js:44:33 {
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: '../../../../todolist_example_jest/req2.js'
}

I can't run commands from nodejs as child_process, or read the file system in an electron application with snap package configuration

I have working on an electron desktop application, the app is quite simple its about building a file browser for Linux. From Nodejs apis I use child_process, fs, path, os, and so on.
I am using electron-builder to package and build the application.
When I build for linux with target like "zip", "deb", "rpm", the application works as expected.
But when I compile for snap. I can't run commands like:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
await exec('which code');
.....
await openExternalApp('code -n', `"${file.path}"`)
.....
async function openExternalApp(cmd, path) {
const util = require('util');
const exec = util.promisify(require('child_process').exec);
await exec(`${cmd} ${path}`);
}
.....
I got an error:
Error: Command failed: which code
at ChildProcess.exithandler (node:child_process:406:12)
at ChildProcess.emit (node:events:390:28)
at maybeClose (node:internal/child_process:1064:16)
at Socket.<anonymous> (node:internal/child_process:450:11)
at Socket.emit (node:events:390:28)
at Pipe.<anonymous> (node:net:687:12) {
killed: false,
code: 1,
signal: null,
cmd: 'which code',
stdout: '',
stderr: ''
}
Error: Command failed: which code
Also in my program when i have to read directories of the file system related with hard drive or another location simply i can't.
I've started to study a little bit the docs in snap store and I realized that you have to configure the slot, layout and slugs to access the whole file system, and perhaps to run bash or shell command like the one above.
After several configuration i continue with the same issues. Here is my configuration for snap in pakage.json
"snap": {
"plugs": [
"desktop",
"desktop-legacy",
"home",
"x11",
"unity7",
"browser-support",
"network",
"gsettings",
"opengl",
"block-devices",
"classic-support",
"hardware-observe",
"home",
"system-backup",
"system-observe",
"process-control",
"hostname-control",
"removable-media",
{
"system-files": {
"read": [
"/etc",
"/usr",
"/home",
"/media",
"/mnt",
"/var",
"/temp",
"/opt",
"/sys",
"/dev",
"/bin",
"/snap"
],
"write": [
"/home",
"/mnt"
]
}
}
],
"desktop": {
"Encoding": "UTF-8",
"Icon": "${SNAP}/icon.png"
}
}
snap image config in pakage.json

RSYNCWRAPPER: rsync exited with code 12

I'm using rsyncwrapper node module.
Here is my code:
rsync({
src: source_path,
dest: dest,
ssh: true,
recursive: true,
privateKey: keystring,
port: port,
args: ['--perms','--rsync-path="mkdir -p '+dest_path+' && rsync"']
},function (error,stdout,stderr,cmd) {
if ( error ) {
// failed
var data_response = {
'Status': 'Failed',
'Message': 'Rsync Failed=>'+error+stdout+stderr+cmd
};
logger.info("[Rsync] Response=>" + JSON.stringify(data_response));
console.log(error.message);
res.json(data_response);
} else {
console.log("Success");
var data_response = {
'Status': 'Success',
'Message': 'Rsync Success'
};
logger.info("[Rsync] Response=>" + JSON.stringify(data_response));
res.json(data_response);
}
});
However I get this error:
[2018-08-07 13:15:33.491] [INFO] JDWF-API - [Rsync] Response=>{"Status":"Failed","Message":"Rsync Failed=>Error: rsync exited with code 12WARNING : Unauthorized access to this system is forbidden and will be\nprosecuted by law. By accessing this system, you agree that your actions\nmay be monitored if unauthorized usage is suspected.\nmkdir: cannot create directory `/DATA/userWorkpace/devteam/7000003': Permission denied\nrsync: connection unexpectedly closed (0 bytes received so far) [sender]\nrsync error: error in rsync protocol data stream (code 12) at io.c(600) [sender=3.0.6]\nrsync /DATA/files/gs/7000003/input// wf-sync#192.168.1.23:/DATA/userWorkpace/devteam/7000003/input// --rsh \"ssh -p 47365 -i /DATA/jdwf-api/secure/wf-sync.dat\" --recursive --perms --rsync-path=\"mkdir -p /DATA/userWorkpace/devteam/7000003/input// && rsync\""}
rsync exited with code 12
I have given 777 permissions to the folder. It doesnt fix it. Can someone help me out please.

Resources