Hello and thank you for your time.
I am trying to make a JavaScript example application working.
The fact is I do not know exactly how to use this static function:
core.utils.js
static parseUrl(url) {
const data = {};
data.filename = '';
data.extension = '';
data.pathname = '';
data.query = '';
let parsedUrl = URL.parse(url);
data.pathname = parsedUrl.pathname;
data.query = parsedUrl.query;
if (data.query) {
// Find "filename" parameter value, if present
data.filename = data.query.split('&').reduce((acc, fieldval) => {
let fvPair = fieldval.split('=');
if (fvPair.length > 0 && fvPair[0] == 'filename') {
acc = fvPair[1];
}
return acc;
});
}
// get file name
if (!data.filename) {
data.filename = data.pathname.split('/').pop();
}
// find extension
let splittedName = data.filename.split('.');
if (splittedName.length <= 1) {
data.extension = 'dicom';
} else {
data.extension = data.filename.split('.').pop();
}
if (!isNaN(data.extension)) {
data.extension = 'dicom';
}
if (data.query &&
data.query.includes('contentType=application%2Fdicom')) {
data.extension = 'dicom';
}
return data;
}
Into the javascript file which has the appliaciton's logic.
I have tried the direct import used by the IDE itself, webstorm in my case:
import CoreUtils from "../../src/core/core.utils";
However, the browser's console says:
Uncaught SyntaxError: Unexpected identifier
And the line where is the error is:
import CoreUtils from "../../src/core/core.utils";
Also I have tried by myself to fix this, and I have read:
Calling a javascript function in another js file
So then I did what Fernando Mendez explains, which is to import the js file in the index.html, as:
<script src="../../src/core/core.utils.js"></script>
So then I commented out the import in the application js:
// import CoreUtils from "../../src/core/core.utils";
And the result is:
Uncaught SyntaxError: Unexpected identifier
In the following line:
import Validators from './core.validators';
Would you be kind and help me a little bit?
In addition my question is related to a previous one:
Javascript Trying to run AMIjs examples in local it does not work
However I do put this separatedly because of I think the problem is with JavaScript and not a Library.
Thank you for reading me.
Are you trying to call the static js function from another js file?
It looks like you have a few problems going on here.
1.) import CoreUtils from "../../src/core/core.utils";
From your example code of CoreUtils, I don't see a exported CoreUtils object from src/core/core_utils.js.
In order to utilize the import statement to reference code in another file, you need to export the object from the original file. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
This can be accomplished quickly by modifying your function definition in core_utils.js as follows:
change static parseUrl(url) { to export function parseUrl(url) {
Then, in application.js:
change import CoreUtils from "../../src/core/core.utils"; to import {parseUrl} from "../../src/core/core.utils"
It looks like you are running into a similar error with import Validators from './core.validators';
Hope that helps!
Try this:
Your parseUrl(url) function should be public, so change static parseUrl(url) to export function parseUrl(url).
Inside your main javascript file, import it like so:
import { parseUrl } from "../../src/core/core.utils";
And then just use it: var parsed = parseUrl(url);
Also, check this out
Related
I am trying to use a global accessToken variable within another file but I keep getting the error Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Taat\Documents\Backend\server\controllers\authController' imported from C:\Users\Taat\Documents\Backend\server\controllers\dataController.js code: 'ERR_MODULE_NOT_FOUND'
where I am exporting it within authController and importing it within dataController as you can see below in the code:
authController.js:
export let accecssToken;
// rest of my code
dataController.js:
import { accecssToken } from "./authController";
export async function getActivityId(req, res) {
const data = await getDataPromise();
const activityIds = {};
for (let i = 0; i < data.length(); i++) {
activityIds[data[i].id] = [];
}
return res.json(activityIds);
}
export async function getDataPromise() {
const link = `api/?access_token=${accecssToken}`;
console.log("Link = ", link);
const response = await axios.get(link);
return response.data;
}
I do not see what I am doing wrong here can anyone spot it?
Both files are in the same directory as you can see from the error messages paths
Just add extension of exported file
import { accecssToken } from "./authController.js";
or You can use
const { accecssToken } = require('./authController');
Use -
const {accessToken} = require("./authController");
Though seeing the naming convention and your code you're utilizing the accessToken, I would not recommend adding SECERTS in js files as it could be compromised.
Make a .env file at the root folder and add all secrets inside.
.env file should look like -
To use any .env variable, add
require("dotenv").config();
and then use -
const link = `api/?access_token=${process.env.ACCESS_TOKEN}`
I need to use this JS file in my vue3 project.
https://gist.github.com/imolorhe/b31f95e1548ad7d1b233de26267fe21c#file-jungle-js
My JS library is
import { Jungle } from "./jungle.js";
async pitchTransform(
audioBuffer,
pitchMod
) {
let ctx = new OfflineAudioContext(
audioBuffer.numberOfChannels,
audioBuffer.length,
audioBuffer.sampleRate
);
let source = ctx.createBufferSource();
source.buffer = audioBuffer;
let pitchChangeEffect = new Jungle(ctx);
}
The application shows this error:
Uncaught SyntaxError: The requested module '/src/js/jungle.js?t=1659194585032' does not provide an export named 'Jungle' (at voiceTransform.js?t=1659199164108:1:10)
What's the recommend way to include and use jungle.js in this setup?
As the error is saying, that file has no export named "Jungle". In fact it has none.
You have to export that function manually, by editing that file and appending an export keyword:
// ...
export function Jungle(context) {
// ...
I have two JavaScript codes.
I would like to import and use another one from one javaScript code.
I tried a few things to import, but there was an error.
This is my main code(main.js):
import * as test from "./noise";
const audioContext = new AudioContext({sampleRate: 48000});
const destination = audioContext.createMediaStreamDestination();
await NoiseNode.register(audioContext)
And, This is the code that I want to import(noise.js):
window.NoiseNode = (window.AudioWorkletNode || (window.AudioWorkletNode = window.webkitAudioWorkletNode)) &&
class extends AudioWorkletNode {
static async register(a) {
k = await h;
await a.audioWorklet.addModule(g + "other.js");
}}
If i try to import as below,
import * as test from "./noise;
These errors occur:
Line 141:15: 'NoiseNode' is not defined no-undef
and then, If i try to import as below,
import * as NoiseNode from "./noise";
These errors occur:
Attempted import error: 'register' is not exported from './noise' (imported as 'NoiseNode').
How can I get everything at once?
Please give me some advice.
Thank you.
You have to export NoiseNode before importing it.
export window.NoiseNode = (window.AudioWorkletNode || (window.AudioWorkletNode = window.webkitAudioWorkletNode)) &&
after exporting, you may import it using the following code:
import * as NoiseNode from "./noise";
I am successfully parsing and evaluating a javascript file with Duktape in my Android application using Kotlin.
val file_name = "lib.js"
val js_string = application.assets.open(file_name).bufferedReader().use {
it.readText()
}
val duktape = Duktape.create()
try {
Log.d("Greeting", duktape.evaluate("'hello world'.toUpperCase();").toString())
duktape.evaluate(js_string)
} finally {
duktape.close()
}
The javascript file was created with Browserify, so it is one single file with everything and it is working fine. But I need to request a module and a method from the module, example:
var test = require('testjs-lib');
test.EVPair.makeRandom().toWTF();
I have no idea of how to do it and have not found any example, besides this link: http://wiki.duktape.org/HowtoModules.html
It tells me to use a modsearch, but I don't have a clue how to do it or where it should be placed, not even if it is applicable for the Duktape Android (https://github.com/square/duktape-android).
Has anybody done it successfully that could shed some light on this matter?
in the testjs-lib.js, add the JS code that makes use of the module testjs-lib.js itself exports. For example:
function myModule() {
this.hello = function() {
return 'hello!';
}
this.goodbye = function() {
return 'goodbye!';
}
}
module.exports = myModule;
//You code goes here
console.log(myModule.hello());
console.log(myModule.goodbye());
Then ask Duktape to evaluate the entire file.
Say you want to include Underscore in duktape.
Put your module/library code in a separate js file. In an android project, you can put this js file in Assets folder. In our example, it'd be sth like: underscore.js
Create a java interface that'd be used by duktape to get inputstream to this js file.
Sth like:
```
public interface DuktapeHelper {
#JavascriptInterface
String getUnderScore();
}
````
Bind this java interface to a js interface in your duktape instance.
```
duktape.bind("helper", DuktapeHelper.class, <instance of your DuktapeHelperImplementation>);
```
Implment modSearch function in duktape using helper interface that you injected before.
```
duktape.evaluate("Duktape.modSearch = function (id) {\n" +
" if (id == \"underscore\") {" +
" return helper.getUnderScore();" +
" } " +
" throw new Error('cannot find module: ' + id);" +
" };" +
"var _ = require('underscore')._; ");
```
All I'm trying to do is execute geoAutocomplete in browser console so I can console log values from form. I'm getting ReferenceError: geoAutocomplete is not defined error.
const GooglePlaces = require('google-places');
const places = new GooglePlaces("myapikey");
function geoAutocomplete(input, lat, long) {
console.log(input, lat, long);
//const dropdown = places.autocomplete(input);
}
export default geoAutocomplete;
myApp.js
import '../sass/style.scss'
import geoAutocomplete from './modules/geoAutocomplete'
geoAutocomplete( document.querySelector('#address'), document.querySelector('#lat'), document.querySelector('#long') );
layout.pug
script(src='/javascript/vcaApp.js' type='module')
form(method='POST' action='/addGeofence')
h3 Add a Geofence
div.input-field
label(for='address') Address
input(type='text' id='address', placeholder='Address',
required='true', autofocus='true' name='address')
div.input-field(style="display: none;")
input(type='number' id='lat', placeholder='Address',
autofocus='true' name='lat')
div.input-field(style="display: none;")
input(type='number' id='long', autofocus='true' name='long')
Just use module.exports / require. It's hard to tell where the error gets produced as you don't know how you're making the code runable in a browser (neither require nor import are supported there).
The easiest will be to just use
module.exports = getAutocomplete;
and to import the function in the other file
const geoAutocomplete = require('./modules/geoAutocomplete');
Your pre es6 compiler/transpiler/whatever will be able to handle this.