NodeJs require error - javascript

I have a nodejs package and i have a linkedList code. I want to include my LinkedList code in my NodeJs js folder but I can't do it. What is the my fault ?
I want to use it like this
This is my code in my NodeJs folder.(app.js)
var KullaniciJS=require('KullaniciLibrary.js');
This is my required folder codes.(KullaniciLibrary.js)
function Kullanici(KullaniciAdi)
{
this.KullaniciAdi=KullaniciAdi;
this.Sonraki=null;
}
function KullaniciListe()
{
this.Bas=null;
this.Uzunluk=0;
}
KullaniciListe.prototype.Ekle=function(EklenecekKullaniciAdi)
{
var Bas=this.Bas;
if (!Bas) {
this.Bas = EklenecekKullaniciAdi;
this.Uzunluk++;
return EklenecekKullaniciAdi;
}
while (Bas.Sonraki!==null) {
Bas = Bas.Sonraki;
}
Bas.Sonraki = EklenecekKullaniciAdi;
this.Uzunluk++;
return EklenecekKullaniciAdi;
};

First you have to declare inside of your KullaniciLibrary.js file, what you want to export. you do this by adding following line at the end of the file:
module.exports = YOUREXPORT;
YOUREXPORT will probably just be the methodname (or some object).
After that, you wanna import it like this:
var KullaniciJS = require('./KullaniciLibrary');
Note that you have to prefix the name with ./ and you don't need to define the file-ending.
If you don't prefix the module with ./, node will search for the module in the node_modules folder, instead of the current directory

In nodejs to require a function from another file you have to export then function.
To export the function use:
module.export='your function name';
and to require the function use:
const variable=require(./filename)
for more understanding use this link:
https://nodejs.org/api/modules.html

Related

node.js using nested functions from different files

I wanted to write a understandable code in node.js, so I want to put some functions, which are used very often, into other node.js files, and access them from there.
So I get a function, which calls a function from another node.js file and in this other node.js file, also another one is called.
Important to know, if I put all in one file, the code works, so it should be an issue with module export and using functions in another file.
I have one file, getting quotes from a decentralised exchange. Looking like this (quoter_uni_v2.js):
module.exports = function quotes_uni_v2(tokenIn, tokenOut, amountIn, router) {
const quotedAmountOut = router.getAmountsOut(amountIn.toString(), [
tokenIn,
tokenOut,
]);
return quotedAmountOut;
};
And I am importing this function in my second helper file (quotes_5.js) (It is splitted in two files, because in the second one I have to call the function multiple times):
var quotes_uni_v2 = require("./quotes_uni_v2");
module.exports = async function (router1, router2, route, amount_wei) {
console.log(route);
var amount_Out = await quotes_uni_v2.quotes_uni_v2(
route[1],
route[2],
amount_wei,
router1
);
...
return (
Math.round(ethers.utils.formatEther(amount_Out[1].toString()) * 100) / 100
);
};
After that I try to call the function in my main.js:
const quotes_uni_v2 = require("./quotes_uni_v2");
const quotes_5 = require("./quotes_5");
async function calc(route) {
amountOut = await new quotes_5(
quickswap_router,
sushiswap_router,
route,
amount_wei
);
return amountOut;
};
But calling the quotes function does not work... The error is:
TypeError: quotes_5 is not a constructor...
Can someone help me?
Thanks!

How to prepend a JavaScript string to every module compiled by Webpack?

I want to prepend a JavaScript string to every module required in my code and compiled by Webpack.
For example, if my entry.js file looks like this:
import _ from 'lodash';
import $ from 'jquery';
import init from './init.js';
init();
I want my output.js bundle to consist of something like this:
function(module, exports, __webpack_require__) {
// prepended JavaScript goes here
// code for lodash module below
}
function(module, exports, __webpack_require__) {
// prepended JavaScript goes here
// code for jquery module below
}
function(module, exports, __webpack_require__) {
// prepended JavaScript goes here
// code for init.js module below
}
function(module, exports, __webpack_require__) {
// prepended JavaScript goes here
var _lodash = __webpack_require__(1);
var _jquery = __webpack_require__(2);
init();
}
I tried writing a simple loader, and it worked, except that it didn't include modules from node_modules since I'm excluding those from my /\.js$/ rule.
So I suspect I need to use a plugin. This is what I have so far:
var pluginName = "PrependJSPlugin";
var apply = (options, compiler) => {
compiler.hooks.compilation.tap(pluginName, compilation =>
compilation.hooks.afterOptimizeModules.tap(pluginName, modules => {
modules.forEach(mod => {
if (mod.resource !== void 0 && mod.resource.includes(".js")) {
var contId = "__WBP_PREPEND__";
var script = `
;var el = document.createElement('pre');
el.innerHTML = '${mod.resource}';
var container = document.getElementById('${contId}');
if (!container) {
container = document.createElement('div');
container.id = '${contId}';
container.appendChild(el);
document.getElementsByTagName('body')[0].appendChild(container);
} else {
container.appendChild(el);
}
`;
mod._source._value = script + mod._source._value;
}
});
})
);
};
module.exports = function(options) {
return {
apply: apply.bind(this, options)
};
};
For the most part, it seems like it's appending it correctly but the compiled output is getting corrupted somehow and I see syntax errors all over the place. I'm definitely doing something I shouldn't be doing with that _source property.
Can someone point me in the right direction?
Why do I want to do this?
This is not something that will go into production. I'm trying to debug a PhantomJS v1 error occurring in a third party service I use for rendering a PDF from an Angular page. Yikes, I know!
I'm catching errors with window.onerror and appending it to the body so they're displayed in the rendered PDF. Unfortunately, the errors don't include source file nor line numbers. So I'm trying to display the name of every module before it runs hoping to see at which one the JavaScript stops executing.

"Reloading" a file in Node.JS

In Node.JS, I'm trying to "reload" a file. I have the following code:
delete require.cache[require.resolve("./pathToFile/" + restartModule)]
with restartModule being the file name, but I'm not sure how I could add the file back using require() and define it as the variable restartModule. For example, if restartModule is myModule, how would I add myModule.js into the var called myModule? Or maybe there's an easier way to simply "reload" a file in the cache?
You could do something simple enough like this:
function reloadModule(moduleName){
delete require.cache[require.resolve(moduleName)]
console.log('reloadModule: Reloading ' + moduleName + "...");
return require(moduleName)
}
var restartModule= reloadModule('./restartModule.js');
You would have to call reloadModule every time you want to reload the source though. You could simplify by wrapping like:
var getRestartModule = function() {
return reloadModule('./restartModule.js');
}
getRestartModule().doStuff();
Or
var reloadModules = function() {
return {
restartModule = reloadModule('./restartModule.js');
};
}
var modules = reloadModules();
modules.restartModule.doStuff();
Or:
var reloadModules = function(moduleList) {
var result = {};
moduleList.forEach((module) => {
result[module.name] = reloadModule(module.path);
});
}
var modules = reloadModules([{name: 'restartModule', path: './restartModule.js'}]);
modules.restartModule.doStuff();
You could even put the module reload on a setInterval so modules would get loaded every N seconds.
Then there's always nodemon: https://nodemon.io/ this is useful in development, whenever a source file changes it will reload your server.
You just use it like node, e.g.
nodemon server.js

Node.js access var issue

My project structure is the following:
project
- js
- *.js
app.js
In my app.js, I define a config variable this way:
try {
var config = yaml.load(program.config);
} catch (e) {
console.error('unable to load configuration, Error:', e.message);
process.exit(1)
}
Which works.
I now would like to access to the content of the var in project/js/*.js, but I got config is undefined.
Why? Isn't config not supposed to be accessible everywhere?
** EDIT **
My code in *.js:
var fetchMail = function() {
console.log(config); // config undefined
// Other stuff
};
And how I export my code in app.js: export.config = config. And then require it in *.js: var app = require(../app);
I assume you need to change
export.config = config to exports.default = config.
If you are exporting something else than exports.config = config.
In other file you need either
import { config } from ..
or
var config = require(...).config;
You should put var config = null on top of try and you than can access the config variable. Initializing var inside try will create the variable inside that scope. Therefore, you can't be accessing config variable.

How do I require() from the console using webpack?

How do I require() / import modules from the console? For example, say I've installed the ImmutableJS npm, I'd like to be able to use functions from the module while I'm working in the console.
Here's another more generic way of doing this.
Requiring a module by ID
The current version of WebPack exposes webpackJsonp(...), which can be used to require a module by ID:
function _requireById(id) {
return webpackJsonp([], null, [id]);
}
or in TypeScript
window['_requireById'] =
(id: number): any => window['webpackJsonp'];([], null, [id]);
The ID is visible at the top of the module in the bundled file or in the footer of the original source file served via source maps.
Requiring a module by name
Requiring a module by name is much trickier, as WebPack doesn't appear to keep any reference to the module path once it has processed all the sources. But the following code seems to do the trick in lot of the cases:
/**
* Returns a promise that resolves to the result of a case-sensitive search
* for a module or one of its exports. `makeGlobal` can be set to true
* or to the name of the window property it should be saved as.
* Example usage:
* _requireByName('jQuery', '$');
* _requireByName('Observable', true)ยด;
*/
window['_requireByName'] =
(name: string, makeGlobal?: (string|boolean)): Promise<any> =>
getAllModules()
.then((modules) => {
let returnMember;
let module = _.find<any, any>(modules, (module) => {
if (_.isObject(module.exports) && name in module.exports) {
returnMember = true;
return true;
} else if (_.isFunction(module.exports) &&
module.exports.name === name) {
return true;
}
});
if (module) {
module = returnMember ? module.exports[name] : module.exports;
if (makeGlobal) {
const moduleName = makeGlobal === true ? name : makeGlobal as string;
window[moduleName] = module;
console.log(`Module or module export saved as 'window.${moduleName}':`,
module);
} else {
console.log(`Module or module export 'name' found:`, module);
}
return module;
}
console.warn(`Module or module export '${name}'' could not be found`);
return null;
});
// Returns promise that resolves to all installed modules
function getAllModules() {
return new Promise((resolve) => {
const id = _.uniqueId('fakeModule_');
window['webpackJsonp'](
[],
{[id]: function(module, exports, __webpack_require__) {
resolve(__webpack_require__.c);
}},
[id]
);
});
}
This is quick first shot at this, so it's all up for improvement!
Including this in a module will allow require([modules], function) to be used from a browser
window['require'] = function(modules, callback) {
var modulesToRequire = modules.forEach(function(module) {
switch(module) {
case 'immutable': return require('immutable');
case 'jquery': return require('jquery');
}
})
callback.apply(this, modulesToRequire);
}
Example Usage:
require(['jquery', 'immutable'], function($, immutable) {
// immutable and $ are defined here
});
Note: Each switch-statement option should either be something this module already requires, or provided by ProvidePlugin
Sources:
Based on this answer, which can be used to add an entire folder.
Alternative method from Webpack Docs - which allows something like require.yourModule.function()
I found a way that works, for both WebPack 1 and 2. (as long as the source is non-minified)
Repo: https://github.com/Venryx/webpack-runtime-require
Install
npm install --save webpack-runtime-require
Usage
First, require the module at least once.
import "webpack-runtime-require";
It will then add a Require() function to the window object, for use in the console, or anywhere in your code.
Then just use it, like so:
let React = Require("react");
console.log("Retrieved React.Component: " + React.Component);
It's not very pretty (it uses regexes to search the module wrapper functions) or fast (takes ~50ms the first call, and ~0ms after), but both of these are perfectly fine if it's just for hack-testing in the console.
Technique
The below is a trimmed version of the source to show how it works. (see the repo for the full/latest)
var WebpackData;
webpackJsonp([],
{123456: function(module, exports, __webpack_require__) {
WebpackData = __webpack_require__;
}},
[123456]
);
var allModulesText;
var moduleIDs = {};
function GetIDForModule(name) {
if (allModulesText == null) {
let moduleWrapperFuncs = Object.keys(WebpackData.m).map(moduleID=>WebpackData.m[moduleID]);
allModulesText = moduleWrapperFuncs.map(a=>a.toString()).join("\n\n\n");
// these are examples of before and after webpack's transformation: (which the regex below finds the var-name of)
// require("react-redux-firebase") => var _reactReduxFirebase = __webpack_require__(100);
// require("./Source/MyComponent") => var _MyComponent = __webpack_require__(200);
let regex = /var ([a-zA-Z_]+) = __webpack_require__\(([0-9]+)\)/g;
let matches = [];
let match;
while (match = regex.exec(allModulesText))
matches.push(match);
for (let [_, varName, id] of matches) {
// these are examples of before and after the below regex's transformation:
// _reactReduxFirebase => react-redux-firebase
// _MyComponent => my-component
// _MyComponent_New => my-component-new
// _JSONHelper => json-helper
let moduleName = varName
.replace(/^_/g, "") // remove starting "_"
.replace(new RegExp( // convert chars where:
"([^_])" // is preceded by a non-underscore char
+ "[A-Z]" // is a capital-letter
+ "([^A-Z_])", // is followed by a non-capital-letter, non-underscore char
"g"),
str=>str[0] + "-" + str[1] + str[2] // to: "-" + char
)
.replace(/_/g, "-") // convert all "_" to "-"
.toLowerCase(); // convert all letters to lowercase
moduleIDs[moduleName] = parseInt(id);
}
}
return moduleIDs[name];
}
function Require(name) {
let id = GetIDForModule(name);
return WebpackData.c[id].exports;
}
Being able to use require modules in the console is handy for debugging and code analysis. #psimyn's answer is very specific so you aren't likely to maintain that function with all the modules you might need.
When I need one of my own modules for this purpose, I assign a window property to it so I can get at it e.g window.mymodule = whatever_im_exporting;. I use the same trick to expose a system module if I want to play with it e.g:
myservice.js:
let $ = require('jquery');
let myService = {};
// local functions service props etc...
module.exports = myService;
// todo: remove these window prop assignments when done playing in console
window.$ = $;
window.myService = myService;
It is still a bit of a pain, but digging into the bundles, I can't see any way to conveniently map over modules.
The answer from #Rene Hamburger is good but unfortunately doesn't work anymore (at least with my webpack version). So I updated it:
function getWebpackInternals() {
return new Promise((resolve) => {
const id = 'fakeId' + Math.random();
window['webpackJsonp'].push(["web", {
[id]: function(module, __webpack_exports__, __webpack_require__) {
resolve([module, __webpack_exports__, __webpack_require__])
}
},[[id]]]);
});
}
function getModuleByExportName(moduleName) {
return getWebpackInternals().then(([_, __webpack_exports__, __webpack_require__]) => {
const modules = __webpack_require__.c;
const moduleFound = Object.values(modules).find(module => {
if (module && module.exports && module.exports[moduleName]) return true;
});
if (!moduleFound) {
console.log('couldnt find module ' + moduleName);
return;
}
return moduleFound.exports[moduleName];
})
}
getModuleByExportName('ExportedClassOfModule');
expose-loader is, in my opinion, a more elegant solution:
require("expose-loader?libraryName!./file.js");
// Exposes the exports for file.js to the global context on property "libraryName".
// In web browsers, window.libraryName is then available.
Adding the below code to one of your modules will allow you to load modules by id.
window.require = __webpack_require__;
In the console use the following:
require(34)
You could do something similar as psimyn advised by
adding following code to some module in bundle:
require.ensure([], function () {
window.require = function (module) {
return require(module);
};
});
Use require from console:
require("./app").doSomething();
See more
After making an npm module for this (see my other answer), I did a search on npms.io and seem to have found an existing webpack-plugin available for this purpose.
Repo: https://www.npmjs.com/package/webpack-expose-require-plugin
Install
npm install --save webpack-expose-require-plugin
Usage
Add the plugin to your webpack config, then use at runtime like so:
let MyComponent = require.main("./path/to/MyComponent");
console.log("Retrieved MyComponent: " + MyComponent);
See package/repo readme page for more info.
EDIT
I tried the plugin out in my own project, but couldn't get it to work; I kept getting the error: Cannot read property 'resource' of undefined. I'll leave it here in case it works for other people, though. (I'm currently using the solution mentioned above instead)
After both making my own npm package for this (see here), as well as finding an existing one (see here), I also found a way to do it in one-line just using the built-in webpack functions.
It uses WebPack "contexts": https://webpack.github.io/docs/context.html
Just add the following line to a file directly in your "Source" folder:
window.Require = require.context("./", true, /\.js$/);
Now you can use it (eg. in the console) like so:
let MyComponent = Require("./Path/To/MyComponent");
console.log("Retrieved MyComponent: " + MyComponent);
However, one important drawback of this approach, as compared to the two solutions mentioned above, is that it seems to not work for files in the node_modules folder. When the path is adjusted to "../", webpack fails to compile -- at least in my project. (perhaps because the node_modules folder is just so massive)

Categories

Resources