Problem with require() function in javascript - javascript

I am trying to implement the following code in which i try to read a json file in javascript. I have two files , let one be main.html which has the main javascript code let it be called main.js , and the other is imported.js
This is the main.html file
<!Doctype html>
<html>
<head>
Dwell time for workers
</head>
<script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="text.json"></script>
<script src="testing_file.js"></script>
<script type = "text/javascript"></script>
<script>
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2]);
</script>
<body>
<h1> worker time : </h1>
</body>
</html>
This is the imported.js file
var that = null;
class import_file
{
constructor(title)
{
this.title = title;
that = this;
}
dwell_times()
{
console.log('osama')
var x = [5,4,3,2,1] ;
var y = x.toString();
console.log(y)
let parsed = require('./updated.json')
console.log(parsed) ;// Arham
return parsed;
}
}
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2])
I am getting the following error
Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (r.js:417)
at Object.localRequire [as require] (r.js:1685)
at requirejs (r.js:2046)
at import_file.dwell_times (testing_file.js:16)
at imported.js:23
What do i do to solve this error ?

Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax :
var moduleName = './updated.json';
require([moduleName], function(fooModule){
// do something
})

Related

JavaScript - Call function from another module inside HTML page

I have a module i18n.js which I import in my home.html, like this:
<html>
<head></head>
<body>
<script type="module" src="../js/lib/i18n.js"></script>
</body>
</html>
Inside the i18n.js module, I do the following:
export const t = () => {};
//
// Global scope
//
window.t = t;
I understand that accessing the global window object is the way to go in order to be able to call a method from other file inside an HTML page. But... why is this code not working?
<html>
<head></head>
<body>
<p><script>t("title")</script></p>
<script type="module" src="../js/lib/i18n.js"></script>
</body>
</html>
I get the error:
Uncaught ReferenceError: t is not defined
Because you're trying to execute t before it's available on the window, you get an error but running the function through the onload as #Rajesh suggested works properly.
const t = () => {
const pTitle = document.getElementById('pTitle');
if (pTitle){
pTitle.textContent = 'Hello World!';
}
};
//
// Global scope
//
window.t = t;
export {
t
};
<html>
<head></head>
<body onload="t()">
<p id="pTitle"> </p>
<script type="module" src="./src/js/i18n.js"></script>
</body>
</html>

Import functions from another js file. Javascript

I have a question about including a file in javascript.
I have a very simple example:
--> index.html
--> models
--> course.js
--> student.js
course.js:
function Course() {
this.id = '';
this.name = '';
}
A student has a course property. like this:
import './course';
function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
}
and the index.html is like:
<html>
<head>
<script src="./models/student.js" type="text/javascript"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
window.onload= function() {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
</body>
</html>
But I am getting an error on the line "var x = new Student();":
Student is not defined
When I remove the import from Student, I don't receive the error anymore.
I have tried to use (require, import, include, create a custom function, export) and none has worked for me.
Anybody knows why? and how to fix that?
P.S. the path is correct, it comes from the autocomplete in VS Code
The following works for me in Firefox and Chrome. In Firefox it even works from file:///
models/course.js
export function Course() {
this.id = '';
this.name = '';
};
models/student.js
import { Course } from './course.js';
export function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
};
index.html
<div id="myDiv">
</div>
<script type="module">
import { Student } from './models/student.js';
window.onload = function () {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
You can try as follows:
//------ js/functions.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import completely:
//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Normally we use ./fileName.js for importing own js file/module and fileName.js is used for importing package/library module
When you will include the main.js file to your webpage you must set the type="module" attribute as follows:
<script type="module" src="js/main.js"></script>
For more details please check ES6 modules
By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.
If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.
import './course.js';
function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
}
<html>
<head>
<script src="./models/student.js" type="module"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
window.onload= function() {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
</body>
</html>
If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.
You can also write a quick express server to serve your files (install Node if you don't have it):
//package.json
{
"scripts": { "start": "node server" },
"dependencies": { "express": "latest" }
}
// server/index.js
const express = require('express');
const app = express();
app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);
With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files.
//In module.js add below code
export function multiply() {
return 2 * 3;
}
// Consume the module in calc.js
import { multiply } from './modules.js';
const result = multiply();
console.log(`Result: ${result}`);
// Module.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Module</title>
</head>
<body>
<script type="module" src="./calc.js"></script>
</body>
</html>
Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error
https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module

Uncaught Error: Module name "antlr4/index" has not been loaded yet for context on require.js

I try to use antlr4 on javascript, then read https://tomassetti.me/antlr-and-the-web/ and make but error has occurred.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="lib/require.js"></script>
<script type="text/javascript">
var antlr4 = require('antlr4/index');
var QueryLexer = require('gram/queryLexer');
var QueryParser = require('gram/queryParser');
document.getElementById("parse").addEventListener("click", function() {
var input = document.getElementById("code").value;
var chars = new antlr4.InputStream(input);
var lexer = new QueryLexer.queryLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new QueryParser.queryParser(tokens);
parser.buildParseTrees = true;
var tree = parser.query();
console.log("Parsed: "+ tree);
});
</script>
</head>
<body>
<div id="inputs">
<textarea id="code">
* play with antlr4
* write a tutorial
</textarea>
<br/>
<button id="parse">Parse</button>
</div>
</body>
</html>
The error may cause on "var antlr4 = require('antlr4/index');".
I downloaded antlr4 from http://www.antlr.org/download/index.html and put same tier of "index.html". In lib directory there exist "require.js".
index.js
exports.atn = require('./atn/index');
exports.codepointat = require('./polyfills/codepointat');
exports.dfa = require('./dfa/index');
exports.fromcodepoint = require('./polyfills/fromcodepoint');
exports.tree = require('./tree/index');
exports.error = require('./error/index');
exports.Token = require('./Token').Token;
exports.CharStreams = require('./CharStreams').CharStreams;
exports.CommonToken = require('./Token').CommonToken;
exports.InputStream = require('./InputStream').InputStream;
exports.FileStream = require('./FileStream').FileStream;
exports.CommonTokenStream = require('./CommonTokenStream').CommonTokenStream;
exports.Lexer = require('./Lexer').Lexer;
exports.Parser = require('./Parser').Parser;
var pc = require('./PredictionContext');
exports.PredictionContextCache = pc.PredictionContextCache;
exports.ParserRuleContext = require('./ParserRuleContext').ParserRuleContext;
exports.Interval = require('./IntervalSet').Interval;
exports.Utils = require('./Utils');
I think there are no problems, because require path('antlr4/index') is not wrong.
But error has occurred. Please give me some idea.
The code you show in your question cannot work as-is with RequireJS. You'd have to write the require calls differently, or wrap all the require calls you have in a define so as to use the CommonJS support that RequireJS provides.
But the tutorial is not asking you to use RequireJS. if you go to the github repo that the writer of the tutorial provided, you'll see:
Require.js was obtained from https://github.com/letorbi/smoothie/blob/master/standalone/require.js
You have to use that file, which is not RequireJS, but something similar to it in the sense that it also loads scripts, and yet different from RequireJS in the sense that it seems to support the CommonJS module format as-is, which RequireJS doesn't.

mocha test client and server side

I'm evaluating mocha but I cant get around some basic problems, I wrote an example test and I'd like to run it both with node.js and in a browser using an html file but I cannot find a way to write only one test that works for both, if I add the require(s) in the test file it's fine for node.js and I get a "Uncaught ReferenceError: require is not defined" in the browser, deleting the require(s) I get "chai is not defined" in node js
this is the code
(function(exports) {
"use strict";
function Cow(name) {
this.name = name || "Anon cow";
}
exports.Cow = Cow;
})(this);
this is the test
var chai = require('chai'),
cowobj = require ("../cow"),
expect = chai.expect;
describe("Cow", function() {
describe("constructor", function() {
it("should have a default name", function() {
var cow = new cowobj.Cow();
expect(cow.name).to.equal("Anon cow");
});
});
this is the html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cow tests</title>
<link rel="stylesheet" media="all" href="node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"><p>Index</p></div>
<div id="messages"></div>
<div id="fixtures"></div>
<script src="node_modules/mocha/mocha.js"></script>
<script src="node_modules/chai/chai.js"></script>
<script src="cow.js"></script>
<script>mocha.setup('bdd')</script>
<script src="./test/cow_test.js"></script>
<script>mocha.run();</script>
</body>
</html>
any Idea on how to fix that?
checking if exports is defined in the test file did the job
if(typeof(exports) !== "undefined"){
var Cow = require ("../cow").Cow,
chai = require('chai');
}
var
expect = chai.expect;
after that I can simply do
var cow = new Cow();

Node.js -- Robust HTML parsing + access to javascript functions in HTML

I'm new to node, and looking to extract javascript info from the following example page:
contrived.html:
<html>
<head>
<title>
This is a contrived example
</title>
<script type="text/javascript">
var filenames = new Array()
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_1.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_2.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_3.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_4.jpg";
function pixplosion_Content()
{
var eElement = document.getElementById('idLoading');
if( eElement ) eElement.style.display = 'none';
return "<pixplosion test=\"test\" flashGasket=\"http://www.realelivepeople.com/pixplosion/assets/flashGasket.swf?contentPath=\" ytBridge=\"/images/image.php?pixplosion=ytbridge\"><tab test=\"test\" label=\"Photos (%1)\" icon=\"Image\" autoIterate=\"false\" ><tab test=\"test\" label=\"Vehicle Photos (%1)\" icon=\"\" autoIterate=\"true\" startFocused=\"true\" >
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102537.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102538.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102539.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102540.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102541.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102542.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102543.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102544.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102545.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102546.jpg</image></tab></tab></pixplosion>";
}
</script>
</head>
<body>
</body>
</html>
Jsdom chokes on this HTML using its default parser, so I've used aredridel/html5 parser from github. It seems to work for reading in HTML, through jQuery, but I don't have access to function definitions like I did with jsdom and its default parser.
For example, the following:
console.log(window.filenames);
With the default parser gives me an array.
With the HTML5 parser, it gives me:
undefined
Here is my code:
var jsdom = require("jsdom"),
fs = require('fs'),
HTML5 = require('html5');
fs.readFile('contrived.html', 'utf-8', function(err, data) {
if (err) {
throw err;
}
var document = jsdom.jsdom(data, null, {parser: HTML5});
// HTML data should be in document creation call
var script = document.createElement("script");
// HTML data SHOULD NOT be in window creation call
var window = document.createWindow();
var parser = new HTML5.Parser({document: window.document});
parser.parse(data);
script.src = 'http://code.jquery.com/jquery-1.4.2.js';
script.onload = function(window) {
console.log('this is a test');
console.log(window.filenames);
console.log(window.pixplosion_Content);
}
document.head.appendChild(script);
});
Am I missing something, or is this functionality just not available?
Many thanks.

Categories