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.
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 an existing Nodejs application that still uses CommonJS, it's been fine up till now but I've ran into a module that I'm not sure how to import. I was hoping there was a fast way of doing it rather than restructuring my whole app to the module standard.
Here is the module's import documentation:
import MetaApi, {CopyFactory} from 'module.cloud-sdk';
const token = '...';
const api = new MetaApi(token);
const copyFactory = new CopyFactory(token);
I got the CopyFactory part to work by destructuring like so:
const { CopyFactory } = require('metaapi.cloud-sdk')
const copyFactory = new CopyFactory(token)
But I can't find a way to import the api aspect with the token, is there anyway of doing it?
Thanks a lot
You can do it this way,
const MetaApi = require('metaapi.cloud-sdk');
const {CopyFactory} = MetaApi;
const token = '...';
const api = new MetaApi.default();
const copyFactory = new CopyFactory(token);
Hopefully this will work fine.
As suggested by Bergi, adding default made it work
const { default: MetaApi, CopyFactory } = require(…)
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
I've made a ModulesManager to manage all my modules, so I don't have a huge list of requirements in the top of my "server.js", but every time I'm trying to access the manager's methods, my server crash and throw an error which is saying that my manager method isn't a function.
TypeError: moduleManager.sqlString is not a function
I'm not really sure what I'm doing wrong here, this might be a stupid error, I've tried to look online for an answer but everyone is saying something different and nothing work.
Modules Manager (manager.js):
const sqlSetup = require("./sqlSetup.js");
const sqlSafeString = require("./sqlString.js");
function Manager(){
this.sqlString = function(query){
return sqlSafeString.getSqlSafeString(query);
},
this.sql = function(){
return sqlSetup;
}
}
module.exports = Manager;
Module SQL (sqlSetup.js):
const SqlString = require('sqlstring');
function getSqlSafeString(query){
//format query to fit in MySQL
var format = SqlString.escape(query);
return format;
}
module.exports = getSqlSafeString;
This is a test for my Travis build that I'm trying to make, the module manager path is good, the problem is really in the "ModuleManager.js" which I don't understand...
require('dotenv').config();
const Discord = require("discord.js");
const client = new Discord.Client();
const token = process.env.MOISTY;
const moduleManager = require("../modules/manager.js");
const assert = require("assert");
console.log("MAKE SURE MOISTY IS OFFLINE!");
client.login(token);
client.on('ready', () => {
//confirm login
console.log("MOISTY:200");
//Assert
assert.deepEqual(moduleManager.sqlString("sample text"), "sample test");
//terminate the session
process.exit();
});
I'm not very used to module exports, so this might be an easy question...
There are multiple mistakes in your code.
module.exports = getSqlSafeString; sets the export to getSqlSafeString.
When you do require("./sqlString.js") you will get the value that was assigned to the exports so in your case the getSqlSafeString.
So if you want to access that function you would write:
const getSqlSafeString = require("./sqlString.js");
//...
return getSqlSafeString(query);`
module.exports = Manager; exports the function Manager but not an object of the type Manager, so moduleManager.sqlString would be equal to Manager.sqlString. If you only want to group the functions in one object, then using a constructor would not make much sense here anyway, so you should write it that way:
module.exports = {
sqlString : function(query){
return sqlSafeString.getSqlSafeString(query)
},
sql : function(){
return sqlSetup
}
};
If you really want to do create on Object of the type Manager then you need to write:
module.exports = new Manager
For you to be able to require something from module A at module B, you have to export that something at module A. You export it assigning it to module.exports.
Yout problem is you didn't export the Manager at the Manager module.
You could simple export Manager, but, because you seem to be using an instance of Manager:
const moduleManager = require("../modules/manager.js");
...
moduleManager.sqlString("sample text")
Then you must export an instance. Add to manager.js:
module.exports = new Manager();
You are putting the functions on an instance, ie this.sqlString is a property named sqlString on an instance of Manager. But you are not using Manager as a constructor, ie not doing new Manager() or in your case new moduleManager()
You can change your import code to like below
const moduleManager = new require("../modules/manager.js")();
Or change the export to:
module.exports = new Manager();
Then moduleManager will be an instance of Manager and will be able to use moduleManager.sqlString