Node | Require is not defined [duplicate] - javascript

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 4 years ago.
Edit : Problem solved using webpack
For the needs of an API, I needed to import MD5 and moment. I downloaded the packages using the basic npm install but when I try to import it on my app.js using the code below :
const md5 = require ('./node_modules/md5/md5.js');
const moment = require ('./node_modules/moment/moment.js');
function getTimeStamp () {
return moment.utc ().format ('YYYYMMDDHHmmss');
}
let timestamp = getTimeStamp ();
function generateSignature (devId, method, authKey, timestamp) {
return md5 (`${devId}${method}${apiKey}${timestamp}`);
}
let signature = generateSignature (XXXX, "createsession", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", getTimeStamp ());
I get this message in the console :
Uncaught ReferenceError: require is not defined
I don't know what I'm doing wrong because I used the same method for another program and it worked perfectly...
Thanks in advance

You're probably seeing this error because require() does not exist in the browser/client-side JavaScript.
If you want to use require() in the browser, then you need to use something like require.js
RequireJS is a JavaScript file and module loader. It is optimized for
in-browser use, but it can be used in other JavaScript environments,
like Rhino and Node.
PS: I agree with cptwonton. Please refer to the mentioned post for an in-depth solution with the various options available.

try this:
const md5 = require ("md5");
const moment = require ("moment");

require isn't supported in a browser because Node and ES6 have their different module systems. Are you trying to call require in a browser? In that case I suggest you to setup Babel. But if you use node, then try reistalling nodejs.

Related

How to load a html to a variable in next.config.js [duplicate]

This question already has answers here:
Module not found: Can't resolve 'fs' in Next.js application
(17 answers)
Closed 8 months ago.
I use standard nextron (Next + electron.js) to jump start my project (https://github.com/saltyshiomix/nextron)
In one particular case, I need to read a file template.html to variable (String). so I think I'll use fs.readFileSync()
When I use import fs from "fs", the compiler complains that fs is not available. (refer to this Module not found: Can't resolve 'fs' in Next.js application)
The accepted answer on that thread, recommends me to update the next.config.js file into:
/// I need this to load image from static files
const withImages = require('next-images')
module.exports = withImages({
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
})
But the solution doesn't work for me.
import fs from 'fs'
const generatePDF = () => {
let content = fs.readFileSync("./template.html")
}
What's wrong here?
I think the problem is that you are trying to use fs module (which is node.js native module) on the client side. The webpack change you've added tells webpack to ignore fs module for the client (or replace it with the stub), but you are still trying to use it.
One way to workaround this is to render your component on the server side only. Please read this documentation - https://nextjs.org/docs/advanced-features/react-18/server-components
Honestly, generally it is bad idea to try to read files/templates on the client side.
But if you really need to get that html on the client, I recommend to create an API which will read html on the server and return as a string. Then you can insert it into the DOM as unsafe html. This will not require massing around with native node modules.
Hope this helps.

ReferenceError: Can't find variable: require - JQuery error

I use this code in my .js file which is part of web site that is used via npm global http-server:
function getParsedStorage() {
let fs = require('fs');
return JSON.parse(fs.readFileSync('./../manager-data.json', 'utf8'));
}
and get errors:
jQuery.Deferred exception: Can't find variable: require (2) (exceptionHook — jquery.min.js:2:31584)
ReferenceError: Can't find variable: require (jquery.min.js:2:31697)
I've installed file-system package with npm install file-system --save but that didn't change anything.
It looks to me like you're attempting to make use of Node.js's require function from within a web browser without using a module system that provides a compatible require method.
Without additional information I can't be certain, however my advice would be to investigate a module loader like Require.js, SystemJS or Browserify which should all enable you to make use of this syntax in your module.
That being said, for the use case you're describing (accessing a JSON file from a website) you may be better served using a simple XHRHttpRequest or the fetch API.
The following is an example which makes use of the fetch API to return the parsed JSON file content.
// Returns a Promise that resolves to the parsed storage data
// NOTE: Lacks any error handling
function getParsedStorage() {
return fetch("../manager-data.json").then(response => response.json())
}

Global variable not working in NodeJS

I am trying to get global variables working in node.js, but it seems like I don't really understand the concept, even though my understanding matches the documentation.
Minimal example
My main.js file, which is compiled using rollup is:
global.a = 1;
require('./core/test.js');
My core/test.js file is simply:
console.log(a);
This causes the error:
Uncaught ReferenceError: a is not defined
The fully compiled output is:
(function (exports) {
'use strict';
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
console.log(a);
commonjsGlobal.a = 1;
}((this.LaravelElixirBundle = this.LaravelElixirBundle || {})));
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjpudWxsLCJzb3VyY2VzIjpbIkM6L3dhbXAvd3d3L3V1YmMvcmVzb3VyY2VzL2Fzc2V0cy9qcy9jb3JlL3Rlc3QuanMiLCJDOi93YW1wL3d3dy91dWJjL3Jlc291cmNlcy9hc3NldHMvanMvYXBwLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImNvbnNvbGUubG9nKGEpO1xyXG4iLCJnbG9iYWwuYSA9IDE7XHJcbnJlcXVpcmUoJy4vY29yZS90ZXN0LmpzJyk7XHJcbiJdLCJuYW1lcyI6WyJnbG9iYWwiXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsT0FBTyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQzs7QUNBZkEsY0FBTSxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUM7OyJ9
It seems that a gets defined after console.log(a);. I'm not 100% sure if this matters in JS but it could be causing the error.
So my question is: what causes this, and what am I doing wrong here?
Possibly relevant information: I'm using Laravel Elixir to compile everything.
Note: Please don't post discussion on whether or not to use global variables in node.js or in general. I know it's usually a bad idea, but I have a very good reason to do it in this case.
Edit: Additional context
What I'm really trying to do is getting Zurb Foundation to work with Laravel Elixir though node.js. I installed foundation-sites through NPM. foundation-sites relies on jquery, which it pulls in itself. However, Foundation doesn't seem to follow the usual conventions of just using something like var jquery = require('jquery'); in its own js file. It actually relies upon a global jQuery variable being available. Therefore I have to ensure that somehow.
My actual file looks like this:
global.jQuery = global.$ = require('jquery');
require('foundation-sites');
So if there are any Foundation/Laravel-specific anwers I would be very happy to hear them as well. Is there something I'm not getting, or did Foundation just not create their package the "right" way?
It looks to me like an issue with your bundler not respecting the order you're doing those two lines in. Your source is clearly:
global.a = 1;
require('./core/test.js');
...but the bundled result is clearly the other way around:
console.log(a);
commonjsGlobal.a = 1;
It seems like it's hoisting the require calls. In general, having require calls that need to be done at a particular point in the execution control flow is not best practice (in fact, when defining modules for ES2015, import is explicitly defined as not being executed in the module's step-by-step control flow).
So if you need to do this, you'll probably want to look at another bundler. But check that it supports order other than dependency resolution order.
You are right that it should work. Here's a working example:
// file1.js
global.a = 'hello';
require('./file2');
// file2.js
console.log(a);
Run node file1.js, and you'll see 'hello' printed to the console.
It looks like you've got some other tool being used (Laravel / Elixir). Use node directly and see what happens.
Alright I solved this in a pretty simple way, by using browserify instead of rollup. Thanks for the other answers pointing me in the right direction. It's not a perfect solution, and I still don't fully understand what the differences are between the two, but it'll do for this project.
The relevant part of my gulpfile:
mix.browserify('app.js','public/js/app.js');
To use browserify with Laravel Elixir, I used
npm install laravel-elixir-browserify-official --save-dev
I solved this for rollup by providing an output.intro that sets up the required variables. In your case this would be:
// rollup.config.js
export default {
// ...
output: {
// ...
intro: `let a = 1;`
}
};
Admittedly this qualifies as a hack, but solves the bundling problem in my case (where switching away from rollup is not an option).

Why i can't requrie SceneExporter in node.js?

Hey guys i got a question, when i wanna use SceneExporter in node.js i got some problem with require it i will show examples:
THREE = require 'three' - here i include module which i instaled to node.js
Export = require './SceneExporter.js' - here is js
ERROR:
THREE.SceneExporter = function () {};
^
ReferenceError: THREE is not defined
How can i use it in node.js ?
Maybe some 1 here did it before.
What's more when i try include three.js from file like here:
THREE = require './three.js'
I get other error:
/home/name/NetBeansProjects/SerwerNode/src/three.js:26561
self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.
^
ReferenceError: self is not defined
I assume you use this bundle of three.js https://github.com/nulltask/node-three.js
Well, it won't solve your problem, but to the question "Why you can't require SceneExporter ?"
the answer is "because this bundle either is not up-to-date with the original repository or it simply does not include the SceneExporter class"
So, what is best approach to solve your dependency problem ?
I don't have the answer yet, but you should keep an eye on the relevant three.js issue here: https://github.com/mrdoob/three.js/issues/4776
Because node.js does not support window/self, which are Web APIs.

Javascript/Node/Twilio - ReferenceError: require is not defined

I have installed Node from:
Node
and run this in cmd:
npm install twilio
I then tried the example code provided by Twilio:
var accountSid = 'MyAccountSidHere';
var authToken = "MyAccountAuthTokenHere";
var client = require('twilio')(accountSid, authToken);
client.sms.messages.create({
body: "Jenny please?! I love you <3",
to: "SomeNumber",
from: "MyNumber"
}, function(err, message) {
process.stdout.write(message.sid);
});
Saved this to MyFile.js file and double clicked it.
I get the error message:
ReferenceError: require is not defined
This is my first encounter with JavaScript and I found a lot of similar questions, but have not been able to solve this.
I am to use this with QML, so I want to load it using:
import "MyFile.js" as MyFile
then call the javascript code as a function.
I've read a little into QML and I don't see how you could use a node.js module in QML. QML is used as a language where QT is the JavaScript engine and node.js is a server-side Javascript engine.
The require() function is a core function of node.js which is part of the engine. It's not something language-specific just like the window object in browser-based Javascript is not something in the Javascript language.
As I said in my comment, you should check out what node.js actually is: a server-side JavaScript engine, which executes JavaScript files. It is not a framework which you could load into another engine like QT.
Your code will run if you use it like this from the command-line:
node MyFile.js
I doubt this is helpful for your use-case as a QML import though.

Categories