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}`
Related
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 some function that needs to be accessed from another file. But for some reason I can't do it.
creatureScreenfunction (dir, jsonFile, pathToFile){
let Mode = require('stat-mode');
let temp;
fs.readdir(dir, function(err, items)
.............................................
}
Here's what I tried
exports.creatureScreen = creatureScreen();
in second file
const index = require("../index.js");
What you did here exports.creatureScreen = creatureScreen(); is named export. While importing it in some other file you need to do const {creatureScreen} = require("../index.js");.
I'm working on a bot using Bot Framework, .env file and a JSON file.
The problem is I can't seem to get the icon to show up unless I set the path manually as shown below:
var invite = new Welcome(process.env.IconUrl = "C:/Users/2203609/Desktop/Mybot/bot.jpg");
That is not a practical way as we will need to change the path manually every time we transfer over to another computer. So I came up with this idea. I will show my .js, .env and .json files.
I create 3 variables namely:
.js:
const loc = '\\bot.jpg';
const pathname = __dirname;
const assa = pathname + loc;
class welcome(){
constructor(IconUrl, botVersion) {
this.IconUrl = IconUrl
this.BotVersion = botVersion
}
}
async Menu(turnContext) {
var invite = new Welcome(process.env.IconUrl = assa);
await turnContext.sendActivity({
attachments: [invite.welcome()]
});
}
.env:
IconUrl =
"items": [{
"type": "Image",
"style": "Person",
"url": "%IconUrl%",
"size": "Large"
}],
The output for this is:
[onTurnError]: SyntaxError: Unexpected token U in JSON at position 633
UPDATE: the variable pathname cannot be used as parameter in welcome class.
There are some errors in how you structured your code. If you wish to display an image you need to use a card. In the example below, I'm using a hero card.
Also, the 'onTurn' method must keep that name. You can create other methods within the class that have their own name. These would reflect different steps within a waterfall dialog. You can read more about waterfall dialogs here.
const { ActivityTypes, CardFactory } = require('botbuilder');
const loc = '\\bot.jpg';
const pathname = __dirname;
const assa = pathname + loc;
const hero = CardFactory.heroCard(
'Hero Card',
CardFactory.images([assa])
);
class Welcome {
constructor(IconUrl, botVersion) {
this.IconUrl = IconUrl;
this.BotVersion = botVersion;
}
async onTurn(turnContext) {
if (turnContext.activity.type === ActivityTypes.Message) {
if (!turnContext.responded) {
const reply = { type: ActivityTypes.Message };
reply.attachments = [hero];
return await turnContext.sendActivity(reply);
}
}
}
}
module.exports.Welcome = Welcome;
I would recommend reading thru the docs. Even more so, I would recommend you look over the various samples on the Botbuilder-Samples GitHub repo. Each sample builds on the previous and introduces core ideas and best practices.
Hope of help!
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 tagged watchman as it MIGHT be the solution I'm looking for, but I don't quite know how to use it in this way!
I have a directory
/imgs
/icons
/bird.png
/cat.png
/dog.png
/pig.png
and I have a file
/imgs/index.js
My index.js is responsible for importing all of the images and then exporting a single object for the rest of my project to use.
const bird = require('./icons/bird.png');
const cat = require('./icons/cat.png');
const dog = require('./icons/dog.png');
const pig = require('./icons/pig.png');
const Icons = { bird, cat, dog, pig };
export default Icons;
What I want to do is watch my imgs folder for new additions, and automatically update my index.js to import these new files and add them to my object. I need to import them with Common.js and export them with ES6.
Does anyone know a good solution to this problem?
A potential solution is to write a JavaScript script that generates your index.js like so:
'use strict';
const fs = require('fs');
const DIR = __dirname + '/imgs/icons';
const output = __dirname + '/imgs/index.js';
return fs.readdir(DIR, (err, files) => {
let result = '';
let references = [];
files.forEach(item => {
// assuming item has the format animal.png
let newReference = item.split('.')[0];
references.push(newReference);
result += `const ${newReference} = require('./icons/${item}');\n`;
});
result += `\nconst Icons = { ${references} };\n\nexport default Icons;`;
fs.writeFile(output, result, err => {
if (err) throw err;
console.log(output + ' updated');
});
});
Place that file (let's call it watcher.js for this purpose) in imgs's parent directory and make watchman run it whenever changes in your icons directory are detected:
watchman imgs/icons "node watcher.js"
Notice that if a new file gets put into the watched directory, the index.js-creating script will not re-run. Only if it gets altered again (even if just gets saved again with the same data), the index.js will reflect that change.
You can simply test that by running touch imgs/icons/crabigator.png twice and look at the watchman log and/or content of index.js.