cannot include a user module in electron (node js) - node.js

file structure
importing the user module connection.js
connection.js
error
This app is based on electron everything is working fine apart from the fact that I cannot require a self created module. It is working fine in the same file just cannot require it externally. I think the renderer somehow cannot find the module.
I have tried setting app to var app = electron.app
and, i have also tried remote but that was a bit defying logic however, it didn't work seriously fed up!!!!!!

Related

Uncaught ReferenceError: require is not defined

I have a project by Three.js.
Like below pic, i have an index.html that uses js codes from scripts.js (in sub-Directory of js).
also, this scripts.js , uses three and OrbitControls libs of package of three.js.
PROBLEM:
after running my project, browser, shows HTML and CSS fine, but it do not works by javascript and gives this error:
i can't find any solution, after half a Day searching & manipulating!
can any one help please?
1)project structure:
root
|------server.js
|------/public
| |---index.html
| |---/js/scripts.js
| |---/css/index.css
2)root/public/index.html:
3)root/public/js/scripts.js:
4)root/server.js:
const express = require("express");
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, '/public')));
app.get('/',function(req,res) {
res.sendFile("public/index.html")
});
app.listen(3000, () => {console.log("listening on port 3000");});
Multiple things going on here. First, require() is nodejs ONLY, is not present in the browser. You are trying to load and run js/scripts.js in the browser and thus cannot use require() in that script.
Separately, when you use type="module" in a script tag, that means the module is an ESM module which can use import to load other modules, but import needs to specify a URL that your express server will handle and serve the right file with.
I'm also guessing that you will have a problem loading the script files because they need to be served by express.static() in your server and need to have the appropriate URL paths in your web page so that express.static() will work. You don't show the server-side file structure for all those scripts so it's hard for us to know exactly what the URLs should be.
And, in the future, please don't ever post screen shots of code. That makes it a lot harder for us to use your code in tests or in answers (because we have to retype it all from scratch) and it can't be searched, is harder to read on mobile, etc... Don't put code in images.

List All Files in Directory React

I am using React.js with Node.js and am trying to serve the client a list of all the files in my (the server's) public folder. I created the app using create-react-app.
I tried using fs but I understood that React is run in a browser environment and that blocks access to file handling so that won't work. After scouring around SO and so many other forums, the closest I got was using require.context but it would return objects with the correct names (of the files) but I couldn't find any way to extract the text from those objects. My code is
const importAll = r => r.keys().map(r);
const files = importAll(require.context('./path/to/folder/', false, /\.*$/));
console.log(files);
I am new to React and web dev in general so I might be missing something.
Thanks in advance!

Re-requiring module that parent requires

I'm in the process of learning NodeJS (using Express), and came across something that struck me as odd.
In app.js i'm requiring a module (passport in this case), and then requiring a second module (passport-strats.js) which I developed. Inside of passports-strats I have to re-require passport even though it's already required in app.js.
This isn't the only example, I have some modules required in three files that are all tightly related. Is this standard or am I missing some crucial piece of structuring NodeJS applications?
For you require the passport module once you should require it in passport-strats.js and export it from this module. In app.js you can use both modules just importing passport-strats.js. ie:
//passport-strats.js
var {passport} = require("./path");
//other code
module.exports = { passport, someVariableFromCurrentModel };
//In app.js
var {passport, someVariableFromCurrentModel} = require("./passport-strats");

require() node module from Electron renderer process served over HTTP

Typically, in an Electron app, you can require node modules from both the main process and the renderer process:
var myModule = require('my-module');
However, this doesn't seem to work if the page was loaded via HTTP instead of from the local filesystem. In other words, if I open a window like this:
win.loadURL(`file://${__dirname}/index.html`);
I can require a node module without problems. But if I instead open a window like this:
win.loadURL(`http://localhost:1234/index.html`);
I no longer can require node modules inside my web page - I get Uncaught Error: Cannot find module 'my-module' in the web page's console. Is there any way to use node modules in an Electron page that was served over HTTP?
A little context: My company is building an application that needs the ability to be hosted as a web application and inside an Electron shell. To make this simpler and consistent across both environments, my Electron app starts a local web server and opens the app hosted at http://localhost:1234. Now I'd like the ability to add spell checking/spelling suggestions into the application using electron-spell-check-provider. This module needs to be imported and initialized inside the renderer process, so I'm trying to require('electron-spell-check-provider') inside my web page, but this fails with the Cannot find module error.
Finally figured this out. In the main process, figure out the absolute path to the node_modules directory, as in:
var nodeModDir = require.resolve('some-valid-module');
var dirnm = 'node_modules';
var pos = nodeModDir.lastIndexOf(dirnm);
if(pos != -1)
nodeModDir = nodeModDir.substr(0, pos+dirnm.length+1);
Now get this path to the renderer process via some IPC. Finally, in the renderer you can now require using an absolute path:
var mymod = require(nodeModDir+'some-valid-module');
Works perfectly for me with electron 1.6.7.
You can add a preload-script which adds a property to the global/window variable. I named mine appRoot. appRoot just has the __dirname value of the preload-script. You then have to go from the folder of the preload-script to your module. I simply use path.join() to make it clean.
This is similar to #logidelic's approach, but without having to mess with IPC messages.
main.js
mainWindow = new BrowserWindow({
webPreferences: {
preload: 'preload.js'
}
})
preload.js:
global.appRoot = window.appRoot = __dirname
index.html:
<script>
const { join } = require('path')
require(join(appRoot, 'rendererApp'))
</script>
Was having a similar issue. Try serving renderer.js over HTTP in your index.html like so,
<script src="/renderer.js"></script>
</body>
Then, as per the docs, load your module in using the adding remote after the require in your renderer.js file.
var spellCheck = require('electron-spell-check-provider').remote;

Webpack-dev-server and isomorphic react-node application

I've managed to properly use webpack dev server alongside with a node server (express), using the plugin section inside webpack's config.
It all works fine but now I'm trying to go isomorphic and use client-side components inside the express application.
So far the only problem I'm encountering is that without webpack 'parsing' my server-side code I get to a situation where I require components but the paths are not solved
I.E.
Inside a component
'use strict';
import React from 'react';
import { RouteHandler, Link } from 'react-router';
import Header from 'components/header/main'; // <-- This line causes the error because webpack is not working when parsing this JSX server-side
export default React.createClass({
displayName: 'App',
render() {
return ( // ... More code
Shall I configure webpack in another way or do I have to change all the imports to be valid server-side?
the codebase is here in case you want to see the actual state https://github.com/vshjxyz/es6-react-flux-node-quickstart
In order to be able to require components in a way such as require('components/Header.js'); and avoid using long relative paths such as require('../../../../../../Header.js'); you can add this code to your node app before any require() calls:
process.env.NODE_PATH = __dirname;
require('module').Module._initPaths();
However, since this relies on a private Node.js core method, this is
also a hack that might stop working on the previous or next version of
node.
Other possible solutions to this problem can be found at https://gist.github.com/branneman/8048520
I see 2 options:
Compile client code with webpack as well. If client's entry
point is in the same dir as server's - it should work with your
present code. This looks natural to me.
Use relative paths i.e.
import Header from './components/header/main'

Resources