Electron with Reactjs execFile error when packing the app - reactjs

I use var child = require("child_process").execFile; to run an external .exe file. When i run the app in debug mode everything runs smoothly. When i build and pack the application then it throws the following error.
Uncaught TypeError: (0 , a(...).execFile) is not a function
My code:
var path = require("path");
export function silentPrintPDF(htmlString) {
var child = require("child_process").execFile;
var executablePath = path.join(
__dirname,
"extraResources",
"ElectronPrinter.exe"
);
var parameters = [htmlString];
child(executablePath, parameters, function(err, data) {
console.log(err);
console.log(data.toString());
});
}
I pack the app with the following command:
"electron:pack": "yarn build && electron-builder build -w"

From my comment, the answer ended up being to use window.require to prevent it getting confused between Electoron's require and Browserify's require.
Source

Related

Error creating StandardAppVersion: googleapi: Error 404: App does not exist

Hi i am trying to create a simple node app on google app standard app engine using this terraform code. This code used to work before but today i was trying to restart the whole project and re-deploy everything again and i see that i am getting an error.
compute_engine.tf
resource "google_app_engine_standard_app_version" "nodetest" {
version_id = "v1"
service = "mainApp"
runtime = "nodejs10"
instance_class = "B1"
basic_scaling {
max_instances = 1
}
entrypoint {
shell = "node test.js"
}
deployment {
files {
name = google_storage_bucket_object.object.name
source_url = "https://storage.googleapis.com/${google_storage_bucket.bucket.name}/${google_storage_bucket_object.object.name}"
}
}
delete_service_on_destroy = true
depends_on = [
google_project_service.appengine_api
]
}
resource "google_storage_bucket" "bucket" {
project = var.project_id
name = var.bucket_name
location = var.region
}
resource "google_storage_bucket_object" "object" {
name = "test.js"
bucket = google_storage_bucket.bucket.name
source = "test.js"
}
My test.js is located in the same directory as where tf is located.
test.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
I see that the files have already been deployed correctly
And the error i am getting
I tried changing the url from
"https://storage.googleapis.com/${google_storage_bucket.bucket.name}/${google_storage_bucket_object.object.name}"
To
"https://storage.cloud.com/${google_storage_bucket.bucket.name}/${google_storage_bucket_object.object.name}"
Try changing the shell = "node test.js" to shell = "node ./test.js"
Also i did take a look at GitHub Issue 4974 but is doesnt solve my problem. I did notice that when i try to terraform apply the error pretty much pop up quite fast so it seem that is stuck on a very first validation error.
Does the user that runs compute_engine.tf has "appengine.applications.create" and deploy permissions?
Also check if you set project and region in your google provider.

How to import minified js file on react create app

So I have this Create react app (I don't really understand webpack), and I wanted to use EaselJS on this one, However the NPM counterpart of EselJS is their version 2 (BETA) and is quite unstable and undocumented - That's why I wanted to use the minified version.
I have a easeljs.min.js on my project but I don't know how to "import it".
doing `import './easeljs.min.js' seems to also generate a lot of linting issues and seems to nor work.
EDIT:
I tried using react-helmet and append it as a script tag, but it seems that react is doing something with the minified version and causes it to error. (unexpected token <)
So I was able to fix it:
I installed react-app-rewired created config-overrides.js and added this code:
module.exports = function override(config, env) {
if (!config.resolve || Object.keys(config.resolve).length === 0) {
config.resolve = {};
}
if (!config.module || Object.keys(config.module).length === 0) {
config.module = {};
}
if (!config.module.rules || config.module.rules.length === 0) {
config.module.rules = [];
}
const resolve = {
alias: {
createjs: "createjs/builds/1.0.0/createjs.js"
}
};
config.resolve = {
...config.resolve,
...resolve
};
config.module.rules.push({
test: /node_modules[/\\]createjs/,
loaders: ["imports-loader?this=>window", "exports-loader?window.createjs"]
});
return config;
};
It seems that it is an issue with createjs itself https://github.com/CreateJS/Combined/issues/12
I also ended up using this repo for createjs.

importScripts in Web Workers is undefined inside a React/Webpack environment

I am working on a React app created with create-react-app. I was having trouble creating a web worker in it so I posted a question here on SO: Creating a web worker inside React
I've found a solution, as written in the post above, to load a worker without ejecting the app and messing with the Webpack config. This is the code, from the post above:
// worker.js
const workercode = () => {
self.onmessage = function(e) {
console.log('Message received from main script');
const workerResult = 'Received from main: ' + (e.data);
console.log('Posting message back to main script');
self.postMessage(workerResult);
}
};
let code = workercode.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));
const blob = new Blob([code], {type: "application/javascript"});
const worker_script = URL.createObjectURL(blob);
module.exports = worker_script;
and in the file that uses the worker:
import worker_script from './worker';
const myWorker = new Worker(worker_script);
myWorker.onmessage = (m) => {
console.log("msg from worker: ", m.data);
};
myWorker.postMessage('im from main');
It works, however, I cannot seem to get importScripts to work. Even if I do this (outside onmessage or inside onmessage):
if (typeof importScripts === 'function') {
importScripts('myscript.js');
}
In that case, the if statement turns out to be true, but then fails on the actual import with the same error message 'importScripts' is not defined as if the if statement is a false positive, which doesn't sound right. I'd say this is a context issue and that the worker probably isn't loading properly (although it seems to work), but it's just a guess.
Any ideas what's happening here?
importScripts in a worker created from Blob works fine, at least in 2021 (react 17.0.2, react-scripts 4.0.3, Chrome 92). The imported script URL must be absolute because worker was created from Blob.
The original issue might have been a bug in webpack or the transpilation might have changed the code in a weird way.
const workercode = () => {
importScripts("https://example.com/extra.js");
console.log(self.extraValue); // 10
self.onmessage = function(e) {
console.log('Message received from main script');
...
}
};
 
// extra.js
self.extraValue = 10;
Looks like this is still broken in 2022 - Seems there is a regression coming down the dev pipeline (at least in Android WebView and possibly some dev/canary chrome verions.)
https://bugs.chromium.org/p/chromium/issues/detail?id=1078821

Using Node.js I get readFileSync is not a function

I am developing a web app with Angular 2, typescript, nodejs and Visual Studio. I want to read a file located in my wwwroot folder. so far I have created the following class:
///<reference path="../../node_modules/angular2/ts/typings/node/node.d.ts"/>
export class LoadConfigurationService {
fs: any;
constructor() {
this.fs = require('fs');
let data = this.fs.readFileSync('input.txt');
}
}
The problem is that I always get the error "readFileSync is not a function". I have tried to install the node file system module by adding the following line
"file-system": "^2.2.1"
to my package.json dependencies. I've also added
"node.TypeScript.DefinitelyTyped": "2.8.8"
to my project.json dependencies. But it keeps giving me the same error. What am I doing wrong?
Your code works for me, such as it is. What error are you getting? Here's the (slightly amended) ts:
declare var require: any;
export class LoadConfigurationService {
fs: any;
public data: string;
constructor() {
this.fs = require('fs');
this.data = this.fs.readFileSync('input.txt').toString();
}
}
const obj = new LoadConfigurationService();
console.log(obj.data);
Run this through tsc v1.8.7 produces:
"use strict";
var LoadConfigurationService = (function () {
function LoadConfigurationService() {
this.fs = require('fs');
this.data = this.fs.readFileSync('input.txt').toString();
}
return LoadConfigurationService;
}());
exports.LoadConfigurationService = LoadConfigurationService;
var obj = new LoadConfigurationService();
console.log(obj.data);
Run this with a suitable input.txt (consisting of "File Contents", for me) in the local directory and get:
$ node temp.js
File Contents
Possible problems
There are a couple issues I can see that might get in your way.
The code depends on the native node fs, not "file-system": "^2.2.1"
The worth of the referenced npmjs library aside, you are invoking the native fs library.
Don't require a dependency inside a constructor.
Dependencies for objects is a problem and worth reading about, but this is not a good way to handle it. fs should be immutable, so there's no advantage to requiring it each time the object is constructed. Just one line at the top of the file will do:
const fs = require('fs');
fs inside Angular?
I'm not sure what the snippet has to do with Angular, but if this code is getting webpacked or browserified things will become difficult. fs is for file system access and bundling that into the browser will not end well.

Simple gulp task to deploy to google app engine and stream output to console?

Is there a good way to execute the gcloud commands to deploy an app to GAE and see the stderr/stdout echoed back at the console? I've tried gulp-exec but it seems to batch up the output, dumping only upon completion. It also won't play nicely when trying to preview locally.
In the end I didn't want to have to use another npm, but loosely inspired by a portion of gulp-run, I came up with the following that assumes a 'clean' and 'build' task exists, and also overrides some constants per environment for a gulp-replace task that is part of my 'build', the key being the spawn of a subshell and piping its output to the current process's:
// gulp deploy [-a dev|staging|prod]
gulp.task('deploy', function() {
var commands = {
remote: 'gcloud preview app deploy app.yaml -q --set-default --project ',
local: 'gcloud preview app run app.yaml'
};
var environments = {
dev: {
app: 'myapp-dev',
},
staging: {
app: 'myapp-staging',
MY_ENDPOINT: 'https://staging.example.com'
},
prod: {
app: 'myapp',
MY_ENDPOINT: 'https://example.com'
}
};
var command = commands.local;
var env = environments[argv.a];
if (env) {
command = commands.remote + env.app;
constantsMap.MY_ENDPOINT = env.MY_ENDPOINT;
}
// Now that our constants are configured, kick off the build, then deploy.
runSequence('clean', 'build', function() {
var title = util.format('$ %s\n', $.util.colors.blue(command));
process.stdout.write(title);
// run the command in its own subshell and pipe the output to our own.
var subshell = childProcess.spawn('sh', ['-c', command]);
subshell.stdout.pipe(process.stdout);
subshell.stderr.pipe(process.stderr);
});
});
This relies on the npms: run-sequence, util, yargs, gulp-load-plugins
If you want to execute commands following code snippet will help you. I have wrapped it inside a promise as you are using gulp:
var cp = require('child_process');
function executeCommand(command, option) {
return new Promise(function (resolve, reject) {
var args = [option.something, option.something];
var ls = cp.spawn(command, args);
var output = "";
ls.on('error', function (err) {
reject(err);
});
ls.stdout.on('data', function (data) {
output += String(data);
console.log(output)
});
ls.on('exit', function (code) {
if (code === 0) {
resolve({
"output": output
});
} else {
reject(Error(output));
}
});
});
}
I am using gulp-gae and it seems it works well.
Supported commands are appcfg.py and dev_appserver.py (in current version). It can be also configured to override some values from the given app.yaml.

Resources