Why can't you read package.json in a builded electron app? - javascript

Hello Stackoverflow users!
I am trying to place all of the configuration for the electron app in the package.json file.
Here is my code snippet:
index.js
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
function readConf() {
const data = fs.readFileSync('./package.json', 'utf8');
return data;
}
ipcMain.on('synchronous-message', (event, arg) => {
event.returnValue = readConfig();
})
index.html
<script type="text/javascript">
const { ipcRenderer } = require('electron')
config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))
</script>
<h1>Version of <script>document.write(config.name)</script> is <script>document.write(config.version);</script></h1>
The code is working when you run the app via npm start, but when you make it into an exe with electron-forge and squirrel (npm make) and try to run it after installing it throws an error that the package.json file can't be found.
So what do you need to specify as the path to the file to read it in the built app?
I am using electron forge.

I found a way to fix the issue!
Instead of
const data = fs.readFileSync('./package.json', 'utf8');
You'll need to write
const data = fs.readFileSync(__dirname + '/../package.json', 'utf8');

Related

How to use a custom made library

I have a AWS dependency layer on on folder nodejs/
There is node_modules/ and package.json with npm dependencies
I created a folder called utils/ and my file is util.js
Since it's a layer on AWS, I import using const utils = require('/opt/nodejs/utils/util'); on my app.js
Problem is that my test cases started failing Cannot find module '/opt/nodejs/utils/util' from 'backend/lambdas/cars/app.js'
How can I fix my test case??
const app = require('./app');
describe('lambda', function () {
it('something', async () => {
const response = await app.lambdaHandler();
....
});
});
app.js
const httpStatusCode = require('http-status-codes');
const cors = require('/opt/nodejs/utils/util');
exports.lambdaHandler = async (event) => {
return {
statusCode: httpStatusCode.OK
};
};
PS: This nodejs folder is on the same level as the lambdas folder
You should import like this const utils = require('../nodejs/utils/util')

ENOENT: no such file or directory, open './data/databases.json'

am trying to write json data from a file contained in model folder to another file inside data folder and the two folders are contained in server folder. but i keep on getting the error message that there is no such file directory. the code below is inside model/model.ts file and the file i want to write to is in data/databases.json and both are inside server folder. i have tried using the following path ./data/databases.json, ../data/databases.json but still not working. the folder is server/models/model.ts
let Products = require("../data/product.json") // i was able to import from the same file can't write to it using the same path
const fs = require("fs")
const creat = (newInfo:any) => {
return new Promise((resolve,reject)=>{
let id = companyInfo.length+1
let value = {...newInfo,"id":id}
companyInfo.push(value)
fs.writeFileSync('../data/databases.json',JSON.stringify(companyInfo, null, 2))
resolve(value)
})
}
export {creat}
i have another file where i call the above function and the folder path is server/controller/controller.ts and below is the code
import {creat} from "../models/model" // importing the function here
import http, { IncomingMessage, Server, ServerResponse } from "http";
const creatCompanyinfo = async (req:IncomingMessage,res:ServerResponse)=>{
let body =""
req.on("data",(chunk)=>{
body += chunk.toString()
})
req.on("end",async ()=>{
let newInfo = JSON.parse(body)
let result = await creat(newInfo)
res.setHeader("Content-Type","application/json")
res.end(JSON.stringify(result))
})
}
export {creatCompanyinfo}
and finally the last file that handles the routing and the path is server/app.ts.
below is the code
import http, { IncomingMessage, Server, ServerResponse } from "http";
import {creatCompanyinfo} from "./controller/controller" //importing the function here
const server: Server = http.createServer((req: IncomingMessage, res: ServerResponse) => {
if(req.url === "/companies" && req.method==="POST"){
creatCompanyinfo(req,res)
}
}
this is the path to the json file am writting to server/data/databases.json
below is the file structure
`server/`
`controller/controller.ts`
`data/databases.json`
`model/model.ts`
`app.ts`
below is the error message am getting
Server Running at Port 4000.....
node:fs:585
handleErrorFromBinding(ctx);
^
Error: ENOENT: no such file or directory, open './data/databases.json'
at Object.openSync (node:fs:585:3)
at Object.writeFileSync (node:fs:2170:35)
at /Users/dec/Challenges/week-5-task-stanzealot/server/lib/models/model.js:28:12
at new Promise (<anonymous>)
at Object.creat (/Users/dec/Challenges/week-5-task-stanzealot/server/lib/models/model.js:24:12)
at IncomingMessage.<anonymous> (/Users/dec/Challenges/week-5-task-stanzealot/server/lib/controller/controller.js:44:36)
at IncomingMessage.emit (node:events:539:35)
Behavior of relative path in import() is different from relative path in fs methods.
import path is relative to source file, but fs path is relative to working directory.
Try converting your path to an absolute path:
const path = require("path");
const aPath = path.resolve(__dirname, '../data/databases.json')
fs.writeFileSync(aPath ,JSON.stringify(companyInfo, null, 2))

Cannot get property of undefined browser window

When running electron 13.1.X and above I get the error - menuHandler.js:8 Uncaught TypeError: Cannot read properties of undefined (reading 'getBrowserWindow').
code from main.js
const { electron, app, Notification, ipcMain } = require('electron');
var Path = require('path');
var url = require('url');
const { BrowserWindow } = require('electron');
The error occurs from menuHandler.js:8
const { remote } = require("electron");
const Window = remote.getBrowserWindow();
And so, I can't use the function:
$("#minimize").click(function() {
Window.minimize();
});
Here it throws an error passing the above message, meanwhile it works fine on older versions of electron. Please how can I fix this?
Remote was removed from the main electron package, you have to install #electron/remote on your project.
To use this new electron remote add this to your main file:
require('#electron/remote/main').initialize();
const { BrowserWindow } = require('electron');
const window = new Browser window();
require("#electron/remote/main").enable(window.webContents);
On your renderer:
const { BrowserWindow } = require('#electron/remote');
Readme of the new remote module: https://github.com/electron/remote#migrating-from-remote

How to set basePath for a static exported NextJS app

I need to build and deploy a React / NextJS app to a Weblogic J2ee server with a specific context. I have some React experience, but taking my first steps with NextJS.
Currently the build/verification steps are;
Create a vanilla NextJS app
Add a next.config.js with a module.export to change the basepath
module.exports = {
basePath: '/test'
}
Execute npm run dev the application is available on 'http://localhost:3000/test'
Add an export script to the package.json "export": "next build && next export" to support static export
Add the export below to resolve issue 21079
//https://github.com/vercel/next.js/issues/21079
module.exports = {
images: {
loader: "imgix",
path: "",
}
}
Executed npm run export to create a static HTML export. Export is completed successfully to the out folder.
When inspecting the index.html in the out folder, all references to the static content still starts with /_next/static and not with /test/_next/static.
So this can be a misinterpretation of my side, please correct me if i am wrong here.
To be able to test the vanilla app on the J2EE applicationserver it has to be packed into a war file. To accomplish this i added the file warpack/warpack.ts to the project.
const fs = require('fs');
const archiver = require('archiver');
const rimraf = require('rimraf') ;
const distFolder = 'dist' ;
const warFile = distFolder + '/test.war';
const buildFolder = 'out';
const contextRoot = 'test';
// Destroy dist folder
rimraf(distFolder, (error) => {
if (!error) {
// Create dist folder
if (!fs.existsSync(distFolder)){
fs.mkdirSync(distFolder);
}
const output = fs.createWriteStream(warFile);
const archive = archiver('zip', {});
output.on('close', () => {
console.log('war (' + warFile + ') ' + archive.pointer() + ' total bytes');
});
// write archive to output file
archive.pipe(output);
// add build folder to archive
archive.directory(buildFolder,'');
// add weblogic.xml
const weblogicXML = '<?xml version="1.0" encoding="UTF-8"?><weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.2/weblogic-web-app.xsd"><weblogic-version>10.3.6</weblogic-version><context-root>' + contextRoot '</context-root><description>Test NextJS</description></weblogic-web-app>'
archive.append(weblogicXML,{ name: 'WEB-INF/weblogic.xml' });
const manifestMF = 'Manifest-Version: 1.0\nBuild-Tag: 0.0.1-SNAPSHOT\nWeblogic-Application-Version: 0.0.1-SNAPSHOT';
archive.append(manifestMF,{ name: 'META-INF/MANIFEST.MF' });
archive.finalize();
} else {
console.log('Failed to delete "' + distFolder + '" folder.') ;
process.exit(1);
};
});
Installed the required packages for webpack.ts
npm install fs --save-dev
npm install rimraf --save-dev
npm install archiver --save-dev
Added the script "warpack": "next build && next export && node warpack/warpack.ts" to build, export and pack the static app to an war.
After deployment of the war-file the page can be loaded on http://something/test but shows an empty page.
Network development tools indicate that the requests are made to the root of the application server, not to the configured basepath.
GET http://host:8001/static/css/main.09371e9d.chunk.css net::ERR_ABORTED 404 (Not Found)
GET http://host/static/js/2.0850eeb7.chunk.js net::ERR_ABORTED 404 (Not Found)
GET http://host/static/js/main.dc0c945b.chunk.js net::ERR_ABORTED 404 (Not Found)
​
Too much focus on basePath value instead on correct syntax of next.config.js.
Second module export in next.config.js overwrote first.
Wrong
module.exports = {
basePath: '/test'
}
//https://github.com/vercel/next.js/issues/21079
module.exports = {
images: {
loader: "imgix",
path: "",
}
}
Correct
module.exports = {
basePath: '/test',
assetPrefix: "/test/",
//https://github.com/vercel/next.js/issues/21079
images: {
loader: "imgix",
path: ""
}
}
You can use env check to invoke only for prod environment if you wish to like:
module.exports = {
basePath: "/test"
assetPrefix: process.env.NODE_ENV === "production" ? "/test/" : undefined,
}

Workbox in Create React App without eject

I'm trying to configure Workbox in CRA without eject. Anyone succeeded?
After hours trialing and error I succeeded to have workbox in CRA. Here's how I did:
First,yarn add -D workbox-build
Next, create a file called build-sw.js in the root folder with:
const fs = require('fs-extra');
const pathmodule = require('path');
const workbox = require('workbox-build');
function build() {
const cwd = process.cwd();
const pkgPath = `${cwd}/node_modules/workbox-sw/package.json`;
const pkg = require(pkgPath);
const readPath = `${cwd}/node_modules/workbox-sw/${pkg.main}`;
let data = fs.readFileSync(readPath, 'utf8');
let path = `${cwd}/build/workbox-sw.js`;
console.log(`Writing ${path}.`);
fs.writeFileSync(path, data, 'utf8');
data = fs.readFileSync(`${readPath}.map`, 'utf8');
path = `${cwd}/build/${pathmodule.basename(pkg.main)}.map`;
console.log(`Writing ${path}.`);
fs.writeFileSync(path, data, 'utf8');
workbox
.injectManifest({
globDirectory: 'build',
globPatterns: ['**/*.{html,js,css,png,jpg,json}'],
globIgnores: ['sw-default.js', 'service-worker.js', 'workbox-sw.js'],
swSrc: './src/sw-template.js',
swDest: 'build/sw-default.js'
})
.then(_ => {
console.log('Service worker generated.');
});
}
try {
build();
} catch (e) {
console.log(e);
}
After that, create a file in src/sw-template.jswith:
(Have in mind that in this file is where you have to put your own cache strategy. See Docs for more info)
workbox.setConfig({
debug: true
});
workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);
workbox.precaching.precacheAndRoute([]);
workbox.skipWaiting();
workbox.clientsClaim();
workbox.routing.registerRoute('/', workbox.strategies.networkFirst());
Finally, in src/registerServiceWorker.js change:
- const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+ const swUrl = `${process.env.PUBLIC_URL}/sw-default.js`;
And in package.json change:
- "build": "react-scripts build && sw-precache --config=sw-precache-config.js'",
+ "build": "react-scripts build && yarn sw",
+ "sw": "node build-sw.js"
Hope it helps!
With the merge of this PR, Create React App 2 now support supports Workbox out of the box, since it now uses workbox-webpack-plugins internally.
Take a look at the official docs to learn more: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

Categories

Resources