Electron: Uncaught Error: Cannot find module - javascript

I'm building my first electron desktop app and I'm getting a "cannot find module" error when I use require() in one file to import the other. Both files are in the same folder and there's no misspelling..
Here's the main file index.js
const app = require('electron')
const store = require('./datacontainer') //Here I import the other file
if(store.users.length==0) { // throws exception: store is not defined
...
}
and below is the imported file datacontainer.js
var exp = module.exports = {};
exp.users = [{user1},{user2},...];
...
However, when I run the app and look at the console, it throws the following exeption;
Uncaught Error: Cannot find module './datacontainer'
at Module._resolveFilename (module.js:543)
at Function.Module._resolveFilename (C:\mm_apps\report-viewer\node_modules\electron\dist\resources\electron.asar\common\reset-search-paths.js:35)
at Function.Module._load (module.js:473)
at Module.require (module.js:586)
at require (internal/module.js:11)
at index.js:10
What am I doing wrong or missing?
UPDATES:
In the index.html where the index.js is used, the error goes away if I reference the script like the following
<script>
require('./scripts/index')
</script>
but throws above error when referenced this way
<script src="./scripts/index.js"></script>
what gives?

When you do
<script src="./scripts/index.js"></script>
it looks for the file on the server.
Something like:
https://www.example.com/your-web-folder/scripts/index.js
Using Node.js's require resolves it according to the folder structure of your project.

Related

Error when import of node module 'windows' in electrons

I am updating the node module of an application made by somebody else. The module used is 'windows' and the version that was used was 0.0.8. I updated electronjs to 22 and the node module 'windows' to the latest version 0.1.2.
I am using the module, as it was used before :
const windows = require('windows');
var a = windows.registry('/RegistryPath/').SomeValueName.value;
And I am getting the error :
A JavaScript error occurred in the main process
Uncaught Exception:
TypeError: Cannot read properties of undefined (reading 'split')
at Object.
(/path/node_modules/windows/lib/runnable.js:9:29) at
Module._compile (node:internal/modules/cjs/loader:1141:14) at
Module._extensions..js (node:internal/modules/cjs/loader:1196:10)
at Module.load (node:internal/modules/cjs/loader:1011:32) at
Module._load (node:internal/modules/cjs/loader:846:12) at f._load
(node:electron/js2c/asar_bundle:2:13328) at Module.require
(node:internal/modules/cjs/loader:1035:19) at require
(node:internal/modules/cjs/helpers:102:18) at Object.
(/path/node_modules/windows/index.js:4:17) at
Module._compile (node:internal/modules/cjs/loader:1141:14)
The error location is at runnable.js:9 :
var path = require('path');
var fs = require('fs');
var exists = require('./utility').exists;
var resolve = require('./utility').resolve;
var PATH = process.env.Path.split(';').filter(function(s){ return ~s.indexOf('node') });
I tried to read the environnemental variable in Linux and I found that if I modify the code of the module 'windows' to get process.env.PATH.split(';') instead of process.env.Path.split(';') I don't get the same error. The code move forward to the next conditional loop. But the filter of the line discussed here is looking for the string 'node'. In the case of an electron app when it is package there is no node_module folder. So I also hit the same next error when the app is package; which is :
//Bugfix taken from #schmittberger
if (!exists(PATH)) {
if (process.env.NODE_PATH) {
PATH = process.env.NODE_PATH
} else {
throw new Error('No bin-PATH found');
}
}
At this point I am receiving the Error('No bin-PATH found'). I don't have enough experience to know how to fix such an issue. Even if I add the path to my node bin in the environnemental variable of Linux I will hit the same error when the app is package for Windows as there are no folder "node_modules" in the packaged app.

Uncaught ReferenceError: require is not defined (How to use a javascript library from the command line, or an html file)

I'm new to javascript and programming in general. I would like to use this:
https://github.com/CesiumGS/gltf-pipeline
It's a tool to convert models into compressed formats.
This is my code:
const gltfPipeline = require("gltf-pipeline");
const fsExtra = require("fs-extra");
const processGltf = gltfPipeline.processGltf;
const gltf = fsExtra.readJsonSync("model.gltf");
const options = {
dracoOptions: {
compressionLevel: 10,
},
separateTextures: true,
};
processGltf(gltf, options).then(function (results) {
fsExtra.writeJsonSync("modeldraco.gltf", results.gltf);
console.log('done');
const separateResources = results.separateResources;
for (const relativePath in separateResources) {
if (separateResources.hasOwnProperty(relativePath)) {
const resource = separateResources[relativePath];
fsExtra.writeFileSync(relativePath, resource);
}
}
});
I copied this file, saved it as compress.js (because it rhymes) and I then ran it with
node compress.js - this is how I'd run a python file.
Error is: Cannot find module 'gltf-pipeline' which makes sense. So, I did:
node -r gltf-pipeline compress.js but I get the same error.
So, I moved to HTML/JS, where I made an index.html file and linked with a <script> tag compress.js and the gltf-pipeline index.js file. These are the errors:
index.js:3 Uncaught ReferenceError: module is not defined
at index.js:3
(anonymous) # index.js:3
compress.js:3 Uncaught ReferenceError: require is not defined
So how is this done? Either as a webpage or command line would be helpful.
This is my folder structure by the way, maybe that's the issue.
basefolder|
|- gltf-pipeline| library files in here
|- compress.js
|- index.html
|- model.gltf
gltf-pipeline works when used as a command line tool.
No.
You can't do that with Javascript.
JS is served to the client.
Whilst NodeJS runs on a server.
These are the differences between node and browser JS.
also for the module error try
npm install gltf-pipeline
Look at NPM to install Node Packages
Also take a look at the NodeJS Tutorial

Error: A dynamic link library (DLL) initialization routine failed on electron but it's fine on node js

I'm trying to load a custom module in electron written in D with node_dlang package, which is fine with node, but it fails within electron.
the test with node, that runs just fine, goes like this:
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule != null);
assert(nativeModule.ultimate() == 42);
But when I went to use it within electron.js, through the preload script, it returns in an error.
the preload script goes like this:
const {
contextBridge,
ipcRenderer
} = require("electron");
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule.ultimate() == 42);
function pageLoaded()
{
// ...
}
window.addEventListener('DOMContentLoaded', pageLoaded);
the error when I attempt to load the module within electron application is:
A JavaScript error occured in the browser process
--------------------------- Uncaught Exception: Error: A dynamic link library (DLL) initialization routine failed.
\\?\C:\Users\001\Desktop\ele\module.node
at process.func [as dlopen] (VM70 asar_bundle.js:5)
at Object.Module._extensions..node (VM43 loader.js:1138)
at Object.func [as .node] (VM70 asar_bundle.js:5)
at Module.load (VM43 loader.js:935)
at Module._load (VM43 loader.js:776)
at Function.f._load (VM70 asar_bundle.js:5)
at Function.o._load (VM75 renderer_init.js:33)
at Module.require (VM43 loader.js:959)
at require (VM50 helpers.js:88)
at Object.<anonymous> (VM88 C:\Users\001\Desktop\ele\preload.js:6)
What's causing this and how do I fix this?
version
node version is: v14.17.0
electron.js: v13.1.1
both are 64-bit.
the module source code goes like this:
import std.stdio : stderr;
import node_dlang;
extern(C):
void atStart(napi_env env)
{
import std.stdio;
writeln ("Hello from D!");
}
int ultimate()
{
return 42;
}
mixin exportToJs! (ultimate, MainFunction!atStart);
it's compiled with dub command line. No arguments.
UPDATE 1 Do I need to rebuild this module? I found this but it didn't work for me either. I installed the electron-rebuild package by npm install --save-dev electron-rebuild and rebuild with .\node_modules\.bin\electron-rebuild.cmd -v 13.1.1 the command ran fine but I still got same error.
UPDATE 2: inside the console, I clicked in the javascript source code file link in the error message (from the exception) it points to this line of code, where there's this comment saying that:
no static exports found
what does that mean? is this related to the methods in D class? they're marked as public... not sure if related
Electron is a Windows-Application and therefore you need to remove output to std. Try to remove
import std.stdio : stderr;
and
import std.stdio;
writeln ("Hello from D!");
and retry import to Electron.
Please refer this (https://stackoverflow.com/a/74280836/9558119) post from me regarding same. Since it is electron build might be missing Visual C++ Build Environment: Visual Studio Build Tools

How do I import another file in JS?

So I'm trying to import another file in JS and I keep getting errors. The main file is script.js and I'm trying to import CookieManager.js. I first tried using
var cookies = require('/CookieManager.js');
but that caused this error: Uncaught ReferenceError: require is not defined. I found out that this happends because require is only supported by Node.js and therefore is causes an error when trying to run it in a browser. I then tried using
import {getCookie} from "../CookieManager";
and set it as an export function which caused this:
Uncaught SyntaxError: Cannot use import statement outside a module
. To fix that, I changed the type of the file from text/javascript to module in HTML. This happened: net::ERR_ABORTED 404 (Not Found). Finally, I tried using
JQuery (`$.getScript('/CookieManager.js', function()`)
but that also resulted in an error:
jquery.min.js:2 GET http://localhost:63342/CookieManager.js?_=1591679474637 404 (Not Found)```
Here is the directory structure:
├───HomePage
│ ├index.html
│ ├style.css
│ ├script.js
├CookieManager.js
Try:
In package.json add:
{"type": "module"}
Then in CookieManager.js:
export function GetCookie() { // your code to import}
Then script.js:
import { GetCookie } from '../CookieManager.js';

NodeJs : TypeError: require(...) is not a function

I am trying to require a file and afterwards pass it to a var. I am following this tutorial to create an authentication system. After writing the server.js file and trying to compile I got a BSON error therefore I changed the line that required the release version of it in mongoose.
Here are my code and error:
server.js
require('./app/routes')(app, passport);
Error
require('./app/routes')(app, passport);
^
TypeError: require(...) is not a function
at Object.<anonymous> (d:\Node JS learning\WorkWarV2\server.js:38:24)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
Process finished with exit code 1
I have read that this usually means that requireJS is not getting loaded properly yet I am not aware why or how to fix it.
Edit due to comment:
As asked, here is the result of console.log(require);
For me, when I do Immediately invoked function, I need to put ; at the end of require().
Error:
const fs = require('fs')
(() => {
console.log('wow')
})()
Good:
const fs = require('fs');
(() => {
console.log('wow')
})()
I think this means that module.exports in your ./app/routes module is not assigned to be a function so therefore require('./app/routes') does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport).
Show us ./app/routes if you want us to comment further on that.
It should look something like this;
module.exports = function(app, passport) {
// code here
}
You are exporting a function that can then be called like require('./app/routes')(app, passport).
One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B) and module B is trying to require(A). When this happens, it will be detected by the require() sub-system and one of them will come back as null and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.
For me, this was an issue with cyclic dependencies.
IOW, module A required module B, and module B required module A.
So in module B, require('./A') is an empty object rather than a function.
How to deal with cyclic dependencies in Node.js
Remember to export your routes.js.
In routes.js, write your routes and all your code in this function module:
exports = function(app, passport) {
/* write here your code */
}
For me, I got similar error when switched between branches - one used newer ("typescriptish") version of #google-cloud/datastore packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports value. I got the error because node_modules still had newer modules used by branch I switched from.
I've faced to something like this too.
in your routes file , export the function as an object like this :
module.exports = {
hbd: handlebar
}
and in your app file , you can have access to the function by .hbd
and there is no ptoblem ....!
I don't know how but in may case it got fixed when I changed
require('./routes')(app)
to
require('./routes')
In my case i fix when i put the S in the module.exportS,
BEFORE:
module.export = () => {}
AFTER:
module.exports = () => {}

Categories

Resources