Accessing non-existent property of module.exports inside circular dependency NodeJS - javascript

Im having some issues when using module.exports inside NodeJS, and I've followed multiple guides, and im almost certain Im doing it right.
I have to scripts, main.js and event.js. Im trying to share a function from main.js to event.js, but its not working. Here is the code:
Main.js
function Scan(){
if(fs.readdirSync('./events/').length === 0){
console.log(colors.yellow('Events Folder Empty, Skipping Scan'))
} else {
var events = fs.readdirSync('./events/').filter(file => file.endsWith('.json'))
for(const file of events){
let rawdata = fs.readFileSync('./events/' + file);
let cJSON = JSON.parse(rawdata);
}
events.sort()
tevent = events[0]
StartAlerter()
}
}
module.exports = { Scan };
Event.js
const main = require('../main')
main.Scan;
This returns the error:
(node:19292) Warning: Accessing non-existent property 'Scan' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
What am I doing wrong?

I discovered that the arrangement had no effect in the error.
I simply changed the way I exported the function from the Main.js
from:
module.exports = { Scan };
to:
exports.Scan = Scan
And in Event.js, I was able to access the file like this
const main = require("./Main.js");
let result = main.Scan();
This solved my problem, I hope it helps another developer 😎

Problem solved, heres what I did differently:
module.exports = { Scan };
Is declared before the Scan function is defined, like so:
module.exports = { Scan };
function Scan(){
//Code
}
Then in event.js, I wrote
const main = require('../main')
As it is now a module, and can be used with the require() function.
Then to execute the funciton in event.js, I write
main.Scan()
To execute it.

better try :
module.exports = Scan;

I am gonna answer it using a simple example, like in this case below:
File A has 3 functions to process database activity: function
addDB, updateDB, and delData;
File B has 2 functions to process User activity on smartphone:
function addHistory, and editHistory;
Function updateDB in file A is calling function editHis in file B, and function editHistory is calling function updateDB in file A. This is what we called circular-dependency. And we need to prevent it by only giving output of state from editHistory and the rest will be processed inside file A.
//ORIGINAL FUNCTIONS which caused CIRCULAR DEPENDENCY
function updateDB() {
//process update function here
//call function in fileB
const history = require("fileB.js");
await history.editHistory(data).then((output) => {
if(output["message"] === "success"){
response = {
state: 1,
message: "success",
};
}
});
return response;
}
//THIS is the WRONG ONE
function editHistory() {
//process function to edit History here
//call function in fileA
const file = require("fileA.js");
await file.updateDB(data).then((output) => { //You should not call it here
if(output["message"] === "success") {
output = {
state: 1,
message: "success",
};
}
});
return output;
}
//==================================================//
//THE FIX
function updateDB() {
//process function here
const history = require("fileB.js");
await history.editHistory(data).then((output) => {
if(output["message"] === "success"){
await updateDB(data).then((output) => {
response = {
state: 1,
message: "success",
};
});
} else {
log("Error");
}
});
return response;
}
function editHistory() {
//process function to edit History here
// No more calling to function inside the file A
output = {
state: 1,
message: "success",
};
return output;
}

Related

Can I read and execute dynamic script file using webpack?

I wondering if it possible to load script dynamic by webpack.
I create a nodejs application with webpack 5 configuration and typescript. (ts-loader).
And I want the application will be able to run module-script file that I'll give by reading the config file I created.
Something like that:
app.ts:
const config = JSON.parse(fs.readFileSync('./app.config.json', 'utf-8'));
import(config.fn).then(m => { console.log({ m }); m.foo(); })
app.config.json:
{ fn: 'path/to/fn.js' }
path/to/fn.js:
exports = function foo() { console.log('in foo'); }
The problem is when I type the filename hard-coded in import it's works, but when i pass using variable it not work.
I wondering if webpack can do it? because I getting error:
uncaught (in promise) Error: Cannot find module './foo.js'
The code:
console.clear();
const foo = './foo.js';
// not works :(
import(foo).then((m) => {
console.log({ m });
});
// not works :(
// require(foo).then((m) => {
// console.log({ m });
// });
//works:
// import('./foo').then((m) => {
// console.log({ m });
// });
stackblitz

Function returning undefined when exported

I created a module in node.js that has 2 functions - takeInput and getEventEmitter. Both of them are exported. But when I require it is some other file, takeInput works fine but getEventEmitter turns out to be undefined.
Here are the codes:-
// main module.js
function takeInput(db) {
// logic to take input from user
}
function getEventEmitter(db) {
const eventEmitter = new EventEmitter();
console.log(takeInput);
eventEmitter.on('function execution complete', () => takeInput(db));
eventEmitter.emit('function execution complete');
}
module.exports = {
takeInput,
getEventEmitter
}
module where main module.js is exported
const { getEventEmitter } = require('main module');
// Some lines of code ...
getEventEmitter(db); // Error here when this function is called.
The error is as follows
TypeError: getEventEmitter is not a function
Please help.
You will need to export those 2 functions from main module.js
function takeInput(db) {
// logic to take input from user
}
function getEventEmitter(db) {
const eventEmitter = new EventEmitter();
console.log(takeInput);
eventEmitter.on('function execution complete', () => takeInput(db));
eventEmitter.emit('function execution complete');
}
export { takeInput, getEventEmitter }
Then it will work.

dynamically gerDownloadURL from images on firebase storage for display

I have a whole bunch of images that have been uploaded on firebase storage and I want to dynamically retrieve the images and display inside my app screen. This is what I tried so far without success:
I tried out the listFilesAndDirectories function found in the RN firebase storage usage API reference which gives me this error:
Possible Unhandled Promise Rejection (id: 1):
Error: [storage/object-not-found] No object exists at the desired reference.
NativeFirebaseError: [storage/object-not-found] No object exists at the desired reference.
function listFilesAndDirectories(reference, pageToken) {
return reference.list({pageToken}).then(result => {
// Loop over each item
result.items.forEach(ref => {
console.log(ref.fullPath);
});
if (result.nextPageToken) {
return listFilesAndDirectories(reference, result.nextPageToken);
}
return Promise.resolve();
});
}
const storageReference = storage()
.ref('gs://appname445.appspot.com/images');
listFilesAndDirectories(storageReference).then(() => {
storageReference.getDownloadURL();
console.log('Finished listing');
});
the above function prints the log statement "Finished listing' but doesn't display image
I also wrote this function which didn't work, it outputs a maxDownloadRetryError after 3 minutes
function fetchImage() {
reference.getDownloadURL().then(
function(url) {
console.log(url);
},
function(error) {
console.log(error);
},
);
}
fetchImage();
The error message is telling you there is no object at the location of the reference you're using. It's not possible to use getDownloadURL() with a path that isn't an actul file object. You can't use it on prefixes (folders).
If you're trying to get a download URL for each object that you listed with listFilesAndDirectories, you would have to call getDownloadURL() on each and every file object that it finds (not just once for the entire prefix).
It would be more like this:
function listFilesAndDirectories(reference, pageToken) {
return reference.list({pageToken}).then(result => {
result.items.forEach(ref => {
// call getDownloadURL on every object reference
ref.getDownloadURL().then(url => {
console.log(`${fullPath}: ${url}`)
})
});
if (result.nextPageToken) {
return listFilesAndDirectories(reference, result.nextPageToken);
}
return Promise.resolve();
});
}

How I can get access to API in the global command file?

I want to create a global command in the nightwatch.js framework when I do that in page object_file without global command function
navigateWithNav() {
return navigateWithNavToolbar.call(this, "#home-nav")
},
Everything works correctly. But when I trying change function in the object _file, on global command I will get undefined for this.api, how I can resolve it?
// page_oject file
navigateWithNav() {
return this.navigateWithNavToolbar("#home-nav")
},
// global command file
const { client } = require("nightwatch-cucumber")
const { MID_TIMEOUT } = global.config.timeouts
exports.command = async function navigateWithNavToolbar(selector) {
return this.api.url(async (url) => {
// if we are someplace which doesnt have the nav toolbar, then
// goto the homepage
if (!url.value.includes(client.launch_url)){
await client.url(client.launch_url)
}
await this.api.waitForElementPresent(selector, MID_TIMEOUT, false)
await this.api.click(selector)
})
}
I don't know about the syntax that the page_oject file code is in, but you want to do something like this to bind this:
navigateWithNav = () => this.navigateWithNavToolbar("#home-nav")

Import a module from string variable

I need to import a JavaScript module from an in memory variable.
I know that this can be done using SystemJS and Webpack.
But nowhere can I find a good working example nor documentation for the same. The documentations mostly talks of dynamic import of .js files.
Basically I need to import the module like below
let moduleData = "export function doSomething(string) { return string + '-done'; };"
//Need code to import that moduleData into memory
If anyone can point to documentation that will be great
There are limitations in the import syntax that make it difficult to do if not impossible without using external libraries.
The closest I could get is by using the Dynamic Import syntax. Two examples follow: the first one is the original I wrote while the second one is an edit from a user that wanted to modernize it.
The original one:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
var moduleData = "export function hello() { alert('hello'); };";
var b64moduleData = "data:text/javascript;base64," + btoa(moduleData);
</script>
<script type="module">
async function doimport() {
const module = await import(b64moduleData);
module.hello();
}
doimport();
</script>
</body>
</html>
The modernized one:
function doimport (str) {
if (globalThis.URL.createObjectURL) {
const blob = new Blob([str], { type: 'text/javascript' })
const url = URL.createObjectURL(blob)
const module = import(url)
URL.revokeObjectURL(url) // GC objectURLs
return module
}
const url = "data:text/javascript;base64," + btoa(moduleData)
return import(url)
}
var moduleData = "export function hello() { console.log('hello') }"
var blob = new Blob(["export function hello() { console.log('world') }"])
doimport(moduleData).then(mod => mod.hello())
// Works with ArrayBuffers, TypedArrays, DataViews, Blob/Files
// and strings too, that If URL.createObjectURL is supported.
doimport(blob).then(mod => mod.hello())
You will however notice that this has some limitations on the way the import code is constructed, which may not precisely match what you need.
The simplest solution is probably to send the code of the module on the server for it to generate a temporary script to be then imported using a more conventional syntax.
let moduleData = await import("data:text/javascript,export function doSomething(str) { return str + '-done'; }");
and to test it
moduleData.doSomething('test');
Use nodejs flag --experimental-modules to use import ... from ...;
node --experimental-modules index.mjs
index.mjs:
import fs from 'fs';
let fileContents = "export function doSomething(string) { return string + '-done'; };"
let tempFileName = './.__temporaryFile.mjs';
fs.writeFileSync(tempFileName, fileContents);
console.log('Temporary mjs file was created!');
import(tempFileName)
.then((loadedModule) => loadedModule.doSomething('It Works!'))
.then(console.log)
Further reading here
How It Works:
I first create the file with fs.writeFileSync
then I use import method's promise to load module and
pipe doSomething method call with "It Works!"
and then log the result of doSomething.
Credits: https://stackoverflow.com/a/45854500/3554534, https://v8.dev/features/dynamic-import, #Louis
NodeJS:
// Base64 encode is needed to handle line breaks without using ;
const { Module } = await import(`data:text/javascript;base64,${Buffer.from(`export class Module { demo() { console.log('Hello World!') } }`).toString(`base64`)}`)
let instance = new Module()
instance.demo() // Hello World!
You can create component and Module on fly. But not from string. Here is an example:
name = "Dynamic Module on Fly";
const tmpCmp = Component({
template:
'<span (click)="doSomething()" >generated on the fly: {{name}}</span>'
})(
class {
doSomething(string) {
console.log("log from function call");
return string + "-done";
}
}
);
const tmpModule = NgModule({ declarations: [tmpCmp] })(class {});
this._compiler.compileModuleAndAllComponentsAsync(tmpModule).then(factories => {
const f = factories.componentFactories[0];
const cmpRef = this.container.createComponent(f);
cmpRef.instance.name = "dynamic";
});
Here is the stackblitz
Based on Feroz Ahmed answer, here is a specific example to dynamically load a Vue 3 component from the server via socket.io.
Server-side (Node + socket.io)
socket.on('give-me-component', (data: any, callback: any) => {
const file = fs.readFileSync('path/to/js/file', 'utf-8');
const buffer = Buffer.from(file).toString('base64');
callback(`data:text/javascript;base64,${buf}`);
});
Client-side (Vue 3 + socket.io-client)
socket.emit('give-me-component', null, async (data: any) => {
// Supposes that 'component' is, for example, 'ref({})' or 'shallowRef({})'
component.value = defineAsyncComponent(async () => {
const imp = await import(data);
// ... get the named export you're interested in, or default.
return imp['TheNamedExport_or_default'];
});
});
...
<template>
<component :is="component" />
</template>
For some weird reason, the suggested way of dynamically import()-ing a "data" URL throws an error: TypeError: Invalid URL when done from an npm package code.
The same "data" URL import()s without any errors from the application code though.
Weird.
const module = await import(`data:text/javascript;base64,${Buffer.from(functionCode).toString(`base64`)}`)
<script type="module">
import { myfun } from './myModule.js';
myfun();
</script>
/* myModule.js */
export function myfun() {
console.log('this is my module function');
}

Categories

Resources