how to include node.js modules with following pattern - node.js

a.js
if(typeof(MAIN) == "undefined") var MAIN = {};
(function(_e) {
function SLfunction(yea,mx,dx){
var out = "abc";
return(out)
}
_e.SLfunction = function(yea,mx,dx) {
return SLfunction(yea,mx,dx);
};
}(MAIN));
b.js
if(typeof(MAIN) == "undefined") var MAIN = {};
(function(_e) {
function SLfunction2(yea,mx,dx){
var out = "def";
return(out)
}
_e.SLfunction2 = function(yea,mx,dx) {
return SLfunction2(yea,mx,dx);
};
}(MAIN));
main.js
var MAIN =(a.js)
var MAIN =(b.js)
How to include the modules into main.js so both SLfunction and SLfunction2 able to use. Thanks

Related

Error [ERR_REQUIRE_ESM]: require() of ES Module ...\angular\node_modules\globby\index.js from ...\angular\gulpfile.js not supported

My angular project was perfectly run but for some error I tried to reinstall Nodejs and npm and problems began. After that when I try to use command npm start in my angular project I faced this error:
Error [ERR_REQUIRE_ESM]: require() of ES Module D:...\angular\node_modules\globby\index.js from D:...\angular\gulpfile.js not supported.
Instead change the require of index.js in D:...\angular\gulpfile.js to a dynamic import() which is available in all CommonJS modules.
at Object. (D:...\angular\gulpfile.js:4:14)
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
I didn't know if this reinstalling was my source of problem so I tried to move to my old version of Nodejs and npm but problem is still there.
current version of Nodejs and npm on my system:
D:\...\angular>node -v
v17.7.0
D:\...\angular>npm -v
7.19.1
I've read lots of same questions but answers didn't work for me.
for example I tried to use this solution on my gulpfile.js
And here is my gulpfile.js file:
var gulp = require("gulp");
var path = require('path');
var merge = require("merge-stream");
var globby = require('globby');
var concat = require('gulp-concat');
var less = require('gulp-less');
var uglify = require('gulp-uglify');
var cleanCss = require('gulp-clean-css');
var bundleConfig = require(path.resolve(__dirname, 'bundles.json'));
var production = false;
var styleEntries = {};
var scriptEntries = {};
function processInputDefinition(input) {
var result = [];
for (var i = 0; i < input.length; i++) {
var url = input[i];
if (url.startsWith('!')) {
result.push('!' + path.resolve(__dirname, url.substring(1)));
} else {
result.push(path.resolve(__dirname, url));
}
}
return result;
}
function fillScriptBundles() {
// User defined bundles
for (var k = 0; k < bundleConfig.scripts.length; k++) {
var scriptBundle = bundleConfig.scripts[k];
scriptEntries[scriptBundle.output] = globby.sync(processInputDefinition(scriptBundle.input), {
noext: true
});
}
}
function fillStyleBundles() {
// User defined styles
for (var k = 0; k < bundleConfig.styles.length; k++) {
var styleBundle = bundleConfig.styles[k];
styleEntries[styleBundle.output] = globby.sync(processInputDefinition(styleBundle.input), {
noext: true
});
}
}
function getFileNameFromPath(path) {
return path.substring(path.lastIndexOf('/') + 1);
}
function getPathWithoutFileNameFromPath(path) {
return path.substring(0, path.lastIndexOf('/'));
}
function createScriptBundles() {
var tasks = [];
for (var script in scriptEntries) {
tasks.push(
createScriptBundle(script)
);
}
return tasks;
}
function createScriptBundle(script) {
var bundleName = getFileNameFromPath(script);
var bundlePath = getPathWithoutFileNameFromPath(script);
var stream = gulp.src(scriptEntries[script]);
if (production) {
stream = stream
.pipe(uglify());
}
return stream.pipe(concat(bundleName))
.pipe(gulp.dest(bundlePath));
}
function createStyleBundles() {
var tasks = [];
for (var style in styleEntries) {
tasks.push(
createStyleBundle(style)
);
}
return tasks;
}
function createStyleBundle(style) {
var bundleName = getFileNameFromPath(style);
var bundlePath = getPathWithoutFileNameFromPath(style);
var stream = gulp.src(styleEntries[style])
.pipe(less({
math: 'parens-division'
}));
if (production) {
stream = stream.pipe(cleanCss());
}
return stream
.pipe(concat(bundleName))
.pipe(gulp.dest(bundlePath));
}
function build() {
production = true;
fillScriptBundles();
fillStyleBundles();
var scriptTasks = createScriptBundles();
var styleTasks = createStyleBundles();
return merge(scriptTasks.concat(styleTasks));
}
function buildDev() {
fillScriptBundles();
fillStyleBundles();
var scriptTasks = createScriptBundles();
var styleTasks = createStyleBundles();
console.log("Dynamic bundles are being created.");
return merge(scriptTasks.concat(styleTasks));
}
exports.build = build;
exports.buildDev = buildDev;

mocha test sends `test` as variable to node app

When writing the tests for my entry file, index.js I run into the problem that the command mocha test passes test as an argument to index.js as it uses process.argv to receive parameters to run on a development environment. I had thought that by using something like minimist to name the parameters would fix this, however this problem still remains when running the tests. In this way my tests do not use the object provided in my test suits, as shown in the following code.
How do I get around this, so that when running my tests, it uses the event object I provide in my test set-up and not the command mocha test?
index.js
'use strict';
var _ = require("underscore");
var async = require('async');
var argv = require("minimist")(process.argv.slice(2));
var getprotocol = require("./getProtocol");
var _getprotocol = getprotocol.getProtocol;
var S3rs = require("./S3resizer");
var s3resizer = S3rs.rs;
var objCr = require("./objectCreator");
var createObj = objCr.creator;
var fileRs = require("./fileResizer");
var fileResizer = fileRs.rs;
var configs = require("./configs.json");
var mkDir = require("./makeDir");
var makeDir = mkDir.handler;
exports.imageRs = function (event, context) {
var _path = argv.x || event.path; //argv.x used to be process.argv[2]
console.log("Path, %s", _path);
var _dir = argv.y; // used to be process.argv[3]
console.log(_dir);
var parts = _getprotocol(_path);
var imgName = parts.pathname.split("/").pop();
console.log("imgName: %s", imgName);
var s3Bucket = parts.hostname;
var s3Key = imgName;
var _protocol = parts.protocol;
console.log(_protocol);
// RegExp to check for image type
var imageTypeRegExp = /(?:(jpg)|(png)|(jpeg))$/;
var sizesConfigs = configs.sizes;
var obj = createObj(_path);
// Check if file has a supported image extension
var imgExt = imageTypeRegExp.exec(s3Key);
if (imgExt === null) {
console.error('unable to infer the image type for key %s', s3Key);
context.done(new Error('unable to infer the image type for key %s' + s3Key));
return;
}
var imageType = imgExt[1] || imgExt[2];
// Do more stuff here
};
if (!process.env.LAMBDA_TASK_ROOT) {
exports.imageRs();
}
test.js
describe("imgeRs", function () {
var getprotocol = require("../getProtocol");
var S3rs = require("../S3resizer");
var objCr = require("../objectCreator");
var mkDir = require("../makeDir");
var fileResizer = require("../fileResizer");
describe("Calling S3", function () {
describe("Success call", function () {
var testedModule, eventObj, contextDoneSpy, S3resizerStub, objCreatorStub, getProtocolStub, fakeResults, mkDirStub, fileResizerStub;
before(function (done) {
contextDoneSpy = sinon.spy();
S3resizerStub = sinon.stub(S3rs, "rs");
objCreatorStub = sinon.stub(objCr, 'creator');
getProtocolStub = sinon.stub(getprotocol, "getProtocol");
mkDirStub = sinon.stub(mkDir, "handler");
fileResizerStub = sinon.stub(fileResizer, "rs");
eventObj = {"path": "s3://theBucket/image.jpeg"};
fakeResults = ["resized"];
testedModule = proxyquire("../index", {
'./getProtocol': {
'getProtocol': getProtocolStub
},
'./S3resizer': {
'rs': S3resizerStub
},
'./objectCreator': {
'creator': objCreatorStub
},
'./makeDir': {
'handler': mkDirStub
},
'./fileResizer': {
'rs': fileResizerStub
}
});
S3resizerStub.callsArgWith(5, null, fakeResults);
testedModule.imageRs(eventObj, {done: function (error) {
contextDoneSpy.apply(null, arguments);
done();
}});
});
after(function () {
S3rs.rs.restore();
objCr.creator.restore();
getprotocol.getProtocol.restore();
mkDir.handler.restore();
fileResizer.rs.restore();
});
it("calls context.done with no error", function () {
expect(contextDoneSpy).has.been.called;
});
});
});
});

Ember blueprint that injects environment config?

I'm relatively new to Ember and was wondering if there is a way to create a blueprint/generator that would inject a new value into the environment config while maintaining all existing configuration. Is there some Ember magic that allows an existing file to act as the blueprint template? My ideal implementation would look something like this:
ember g platform foo
// config/environment.js
module.exports = function(environment) {
var ENV = {
// Existing config values here...
APP: {
platforms: {
foo: 'abc123' // Generator injects the 'foo' platform and a GUID
}
};
// Existing environment-specific settings here...
return ENV;
};
Is this something that would be more easily accomplished using Node's fs.readFile() and fs.writeFile()? If so, how could I parse environment.js?
No there's no existing magic in Ember to my knowledge sorry. When you generate a route, something very similar to what you are talking about happens but the code is rather complex. The ember generate route new_route function has a call to this function
function addRouteToRouter(name, options) {
var routerPath = path.join(options.root, 'app', 'router.js');
var source = fs.readFileSync(routerPath, 'utf-8');
var routes = new EmberRouterGenerator(source);
var newRoutes = routes.add(name, options);
fs.writeFileSync(routerPath, newRoutes.code());
}
which then exectutes interpreter level like code to add the router and revert it back to code:
module.exports = EmberRouterGenerator;
var recast = require('recast');
var traverse = require('es-simpler-traverser');
var Scope = require('./scope');
var DefineCallExpression = require('./visitors/define-call-expression.js');
var findFunctionExpression = require('./helpers/find-function-expression');
var hasRoute = require('./helpers/has-route');
var newFunctionExpression = require('./helpers/new-function-expression');
var resourceNode = require('./helpers/resource-node');
var routeNode = require('./helpers/route-node');
function EmberRouterGenerator(source, ast) {
this.source = source;
this.ast = ast;
this.mapNode = null;
this.scope = new Scope();
this.visitors = {
CallExpression: new DefineCallExpression(this.scope, this)
};
this._ast();
this._walk();
}
EmberRouterGenerator.prototype.clone = function() {
var route = new EmberRouterGenerator(this.source);
return route;
};
EmberRouterGenerator.prototype._ast = function() {
this.ast = this.ast || recast.parse(this.source);
};
EmberRouterGenerator.prototype._walk = function() {
var scope = this.scope;
var visitors = this.visitors;
traverse(this.ast, {
exit: function(node) {
var visitor = visitors[node.type];
if (visitor && typeof visitor.exit === 'function') {
visitor.exit(node);
}
},
enter: function(node) {
var visitor = visitors[node.type];
if (visitor && typeof visitor.enter === 'function') {
visitor.enter(node);
}
}
});
};
EmberRouterGenerator.prototype.add = function(routeName, options) {
if (typeof this.mapNode === 'undefined') {
throw new Error('Source doesn\'t include Ember.map');
}
var route = this.clone();
var routes = route.mapNode.arguments[0].body.body;
route._add.call(
route,
routeName.split('/'),
routes,
options
);
return route;
};
EmberRouterGenerator.prototype._add = function(nameParts, routes, options) {
options = options || {};
var parent = nameParts[0];
var name = parent;
var children = nameParts.slice(1);
var route = hasRoute(parent, routes);
if (!route) {
if (options.type === 'resource') {
route = resourceNode(name, options);
routes.push(route);
} else {
route = routeNode(name, options);
routes.push(route);
}
}
if (children.length > 0) {
var routesFunction = findFunctionExpression(route.expression.arguments);
if (!routesFunction) {
routesFunction = newFunctionExpression();
route.expression.arguments.push(routesFunction);
}
this._add(children, routesFunction.body.body, options);
}
};
EmberRouterGenerator.prototype.remove = function(routeName) {
if (typeof this.mapNode === 'undefined') {
throw new Error('Source doesn\'t include Ember.map');
}
var route = this.clone();
var routes = route.mapNode.arguments[0].body.body;
var newRoutes = route._remove.call(
route,
routeName.split('/'),
routes
);
if (newRoutes) {
route.mapNode.arguments[0].body.body = newRoutes;
}
return route;
};
EmberRouterGenerator.prototype._remove = function(nameParts, routes) {
var parent = nameParts[0];
var name = parent;
var children = nameParts.slice(1);
var route = hasRoute(parent, routes);
var newRoutes;
if (children.length > 0) {
var routesFunction = route.expression && findFunctionExpression(route.expression.arguments);
if (routesFunction) {
newRoutes = this._remove(children, routesFunction.body.body);
if (newRoutes) {
routesFunction.body.body = newRoutes;
}
return routes;
}
} else {
if (route) {
routes = routes.filter(function(node) {
return node !== route;
});
return routes;
} else {
return false;
}
}
};
EmberRouterGenerator.prototype.code = function(options) {
options = options || { tabWidth: 2, quote: 'single' };
return recast.print(this.ast, options).code;
};
So then there's the alternative, which involves reading the file, adding in your new environment in the correct place after parsing the file correctly, and then writing the stream back. The complexity of what you are wanting to do probably outweighs the time it would take to do this manually IMO. If this is something you are doing often, maybe consider writing a script in another language that's better(read as more people use it for this) at textual file manipulation

Initialize a module when it's required

I have a module with some initialization code inside. The init should be performed when the module is loaded. At the moment I'm doing it like this:
// in the module
exports.init = function(config) { do it }
// in main
var mod = require('myModule');
mod.init(myConfig)
That works, but I'd like to be more concise:
var mod = require('myModule').init('myConfig')
What should init return in order to keep mod reference working?
You can return this, which is a reference to exports in this case.
exports.init = function(init) {
console.log(init);
return this;
};
exports.myMethod = function() {
console.log('Has access to this');
}
var mod = require('./module.js').init('test'); //Prints 'test'
mod.myMethod(); //Will print 'Has access to this.'
Or you could use a constructor:
module.exports = function(config) {
this.config = config;
this.myMethod = function() {
console.log('Has access to this');
};
return this;
};
var myModule = require('./module.js')(config);
myModule.myMethod(); //Prints 'Has access to this'

node.js - Emit events from an object

I have the following module in node.js:
var obj = {};
obj.prop1 = "value1";
obj.prop2 = "value2";
asyncFunction(function(data) {
obj.prop3 = data;
// I would like to do: obj.emit("completed");
});
module.exports = obj;
So I can import it like:
var imp = require('./obj');
imp.on("completed", function() {
console.log("Hello!");
});
How can I do it?
You will need to make obj an EventEmitter. This can be done pretty simply - just change this:
var obj = {};
To this:
var EventEmitter = require('events').EventEmitter;
var obj = new EventEmitter();

Resources