w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
module.exports in nodejs - fn vs object
var module = fileName.split('.')[0]; is the culprit. Because of how scoping works in JavaScript, that module variable isn't local to the for loop but instead the whole file. Thus, when you use it at the end: module.exports = apiRegistry; you are setting the exports property on your own module variable instead of the one node expects you to use. Changing to using another variable name solves your problem: var apiRegistry = {}; var files = fs.readdirSync('./apis'); for (var index in files) { var fileName = files[index]; var myModule = fileName.split('.')[0]; apiRegistry[myModule] = require('../apis/' + myModule); } // console.log(apiRegistry) --> Prints {key: moduledef ..} module.exports = apiRegistry;

Categories : Javascript

what should nodeJS/commonJS module.exports return
"so that if I choose to return a function and not an object then possibly this implies that on every require It is necessary to actually run this function." It does not matter whether you return an individual function or an object. In neither cases a function (or functions) are ran. unless you explicitly do so. For instance, consider the a module hello.js: exports = function () { return 'Hello'; }; You can use require to get that function: var hello = require('hello'); If you want to run that function, you need to invoke it explicitly as follows: var hello = require('hello')(); You wrote you want to make sure your function is executed exactly once. Intuitively this could lead you to writing your hello.js as follows: var hello = function () { return 'Hello'; }; exports

Categories : Node Js

If a nodejs module exports an object to two other modules, do changes made to that object in one downstream module propagate to the other?
here is the way I do it: var datastore = {}; module.exports = datastore; var redis = require('redis'); var client = ''; var testResults = ''; datastore.CreateDataStore = function(storePort, storeUrl, passwd) { client = redis.createClient(storePort,storeUrl); redisClient.auth(passwd, function() { console.log("redisAuth Connected!"); }); testResults = createSiteUpdater(""); } datastore.setdata = function(data, callback){ client.set(data.key, data.value, callback); } the second function is accessor functions to my database. Not sure that this is the best way, but lets me swap out different databases easily if I need to and should save any changes to the datastore object. Instead of requiring it more than one module, pass the single object around Here is a

Categories : Javascript

Haskell: hide specific function(s) in module exports?
As far as I'm aware there is not currently a way to do this. What I usually end up doing is having a central module that re-exports important things as a convenient way to import everything that is necessary while not hiding anything in the modules defining these things (which in some cases - that you probably won't foresee! - makes it easier for your users to modify things in your module). To do this use the following syntax: -- |Convenient import module module Foo.Import (module All) where -- Import what you want to export import Foo.Stuff as All hiding (local_func) -- You can import several modules into the same namespace for this trick! -- For example if using your module also requires 'decode' from "Data.Aeson" you can do import Data.Aeson as All (decode) You have now convenient

Categories : Haskell

Understanding NodeJS's exports/require
That is what's called a circular dependency (the node docs call it a "cycle") when two modules both require each other. It is almost always a design choice you can and should avoid. Node has to load one module first, so the second one ends up getting an empty object due to this circular dependency edge case. The solution is to not make gets.js require app.js, just have app.js require gets.js. //app.js var app = require('express')(); var gets = require('./gets'); gets.setup(app); then //gets.js function setup (app) { app.get('/blah', myHandler); } exports.setup = setup;

Categories : Node Js

Can I make nodejs addon replacing "exports" object?
You can set myfunc as the exports object by setting module.exports directly: function myfunc() { } module.exports = myfunc; The Modules documentation covers the distinction between exports and module.exports: Note that exports is a reference to module.exports making it suitable for augmentation only. If you are exporting a single item such as a constructor you will want to use module.exports directly instead. function MyConstructor (opts) { //... } // BROKEN: Does not modify exports exports = MyConstructor; // exports the constructor properly module.exports = MyConstructor; As for making it a C++ Addon, a rough example would be: #include <node.h> using namespace v8; Handle<Value> MyFunc(const Arguments& args) { HandleScope scope; return scope.Cl

Categories : Node Js

will exports['delete'] run as exports.delete in nodejs
not only in this case, as far as your parameter is a valid javascript identifier those two are the same, for example: object.name is exactly the same as: object['name'] if name isn't a valid identifier you shall use the second form, and remember the first form is encouraged.

Categories : Node Js

Does Jersey expose a way to manually bind dependencies to an instance?
The JAX-RS way is to implement your own ContextResolver for MyInterface. Then you can manage the implementation of the contexts inside the context resolved. Context resolver is provider and is managed by Jersey, but not the MyInterface implementations.

Categories : Java

Syntax for a single function module targeting the browser and NodeJS
Adapted from Multiple Files communication with coffeescript Basically, we choose whether to run server-side or client-side code based on which environment we're in. This is the most common way to do it: if(typeof module !== "undefined" && module.exports) { //On a server module.exports = ChatService; } else { //On a client window.ChatService = ChatService; } To get it: if(typeof module !== "undefined" && module.exports) { //On a server ChatService = require("ChatService.coffee"); } else { //On a client ChatService = window.ChatService; } The else clause of the second block can be skipped, since ChatService already refers to the reference attached to window. Note that your current code will crash with a ReferenceError on the client, unless module happ

Categories : Javascript

Exporting a prototype in node.js: module.exports=Prototype or exports.Prototype=Prototype?
The second one would only be useful if you exported multiple classes from one file which is something that is questionable by itself. There is no problem in replacing the exports object at all.

Categories : Node Js

Differences between three different ways using module.exports
Differences are small. The difference between #1 and #2 is that myClass (the variable) can be used in other places within the module. The difference between #2 and #3 is that the function has a name, and thus: It is easier to use recursion if you want to (though not impossible in #3) You get nicer-looking stack trace, as you said. (Constructors are sometimes recursive, with the idiom that you can call them both with and without new, and they first check whether this is an instance of MyClass and if not call themselves recursively with new).

Categories : Node Js

Why my module.exports doesn't work?
You don't need to include app in index.js indes.js should just be exports.index = function(req, res){ console.log(server); res.send('Hello world'); }; And I am assuming index.js is in the routes folder like so app.js routes index.js

Categories : Node Js

Why doesn't backbone use module.exports?
Why doesn't backbone use module.exports? Because it doesn't have to. exports and module.exports refer to the same object: In particular module.exportsis the same as the exports object. If you can save a couple of characters to type, then why not do it? You are doing the same when you use document.getElementById instead of window.document.getElementById. It's more to type and doesn't add any benefit. In the tutorial they are using module.exports because they want to show the difference between exporting a symbol why exports, i.e. exports.foo = bar; and overwriting the exports object module.exports = bar; for which you have to use module.exports (exports = bar; would not work).

Categories : Javascript

nodejs async function parameters durability in rapid calls
Consider the following example: function doStuff() { var temp = 0; function modifyTemp(temp) { temp = 5; } modifyTemp(temp); //the value of temp is still 0 function modifyTemp2() { temp = 10; } modifyTemp2(); //temp now equals 10 } doStuff(); Notice that temp is within the closure scope of "doStuff()". So any reference to temp within this scope will use this reference, unless there is one that takes precedence, as in the example of modifyTemp(temp) declaration. In this case, a temp copy of the temp variable is created and stored to "temp" which is modifed within the scope of only this funciton, and the temp defined within the closure is left untouched. So the answer to your question is, it depends on what level of scope you h

Categories : Javascript

can not have require multiple modules with module.exports in it
It looks like you're attempting to pass require() an undefined variable two times. require() needs to take a string as an argument to determine what module you want to load. If the other two modules are in the same directory as app.js, try m1 = require('./module1') m2 = require('./module2') EDIT: What you're forgetting to do is m1 = new require('./module1')() m2 = new require('./module2')() Assuming that you modules look like: module.exports = function() { this.method = function(){} } Personally, instead of a function I would just return an object literal from my module: module.exports = { method1: function(){}, method2: function(){} } Then I could invoke the methods from the module's export like such: m1 = require('./module1'); m1.method1();

Categories : Node Js

Module.exports vs plain json for config files
Thanks @jonathan-ong, looks like config.js (NOT JSON file) works as expected and I could put some comments. module.exports = { // Development Environment development: { database: { host: '127.0.0.1', login: 'dev', password: 'dev' } }, // Production Environment production: { database: { host: '127.0.0.1', login: 'prod', password: 'prod' } } };

Categories : Json

Run nodejs command line module to output in nodejs web server?
you could have 2 node instances. One the http server and the second instance the command line instance to run jasmine. The http server instance would spawn the command line instance. Then you could register a GET route on the http server such as someexample.com/runtests which would call the tests and wait for the tests to finish and respond with the console output. This is sort of unorthodox, but there wouldn't be a direct way to run command line applications through the browser without modifying their source.

Categories : Node Js

node.js expose variable to module?
You can use globals, or have a proper circular dependency (requireing both files), however - this is usually a bad habit which can lead to maintainability problems in the future. Instead, you can use dependency injection and inject doSomething into your module. This basically gives you the following for free: You can test User with a simple mock implementation of doSomething later and verify the correctness of your code The dependencies of a user are explicit and not implicit, which makes it obvious what a user needs. I'll provide two implementations, one using constructor dependency injection and one with a module wide setting. USER.JS function User(dependentFunction) { this.property = 'value'; this.doSomething = function() { var getStuff = dependentFunction(); /

Categories : Javascript

How to expose variable in Python module?
You can wrap your connection information in a class class Database: def __init__(self, **kwargs): if kwargs.get("connection") is not None: self.connection = kwargs["connection"] elif kwargs.get("host") is not None: self.connection = odbi.connect(host) self.cursor = self.connection.cursor() mydb = Database(host="localhost") results = mydb.cursor.execute("select * from foo") #or use it with a connection mydb = Database(connection="localhost") results = mydb.cursor.execute("select * from foo")

Categories : Python

AngularJS: Inject dependencies while $provide
I don't know about lazy loading but, if lazy loading work then the standard method of injection may work service = ['serviceName', '$rootScope','$q', function($rootScope, $q){ return { a: 1, b:2 } }]

Categories : Javascript

How to inject dependencies in app.config in angularjs?
It is because app.config returns reference to the app (for chaining). This code works: var config = function($routeProvider) { $routeProvider .when('/', {controller: 'PageCtrl', templateUrl: '../templates/home.html'}) .otherwise({redirectTo: '/'}); }; config.$inject = ['$routeProvider']; app.config(config); http://jsfiddle.net/ADukg/3196/

Categories : Javascript

Ruby: trying to object.send a module function with parameters
Its not clear from your question how the class Blueprints relates to Settings. I'll assume that either Blueprints is a subclass of Settings or you meant to use Settings instead. What I am expecting is that send() will call the "foreign_function" method, converting the string to a symbol, and then will add the two parameters to the call. You need to call send() on the object (or class) that you want to send() to: foreign_function = 'find_by_name' Blueprints.send(foreign_function, 'name.txt', 'Users/MCP/Desktop/Projects/TestDir')

Categories : Ruby

How to expose a C++ class to Python without building a module
As far as I know, there is no easy way to accomplish this. To extend Python with C++ with neither a module nor an intermediate library, it would require dynamically loading a library, then importing the functions. This approach is used by the ctypes module. To accomplish the same with C++, one would need to write a ctypes-like library that understood the C++ ABI for the target compiler(s). To extend Python without introducing a module, an intermediate library could be created that provided a C API that wraps the C++ library. This intermediate library could then be used in Python through ctypes. While it does not provide the exact calling syntax and does introduce an intermediate library, it would likely be less effort than building a ctypes-like library that could interface directly

Categories : C++

How do I expose module capabilities in an MEF based modular application?
While I don't know of any tutorials for creating a MEF WPF Prism application, I am currently developing many of these apps for work, so I can offer some of the tricks I use. The first thing I'd say is that since you're using MEF, you should use it. You don't need to use the ServiceLocator. Import that IRegionManager! Another thing that I really like about MEF over other IoC containers in Prism is that I don't usually write an IModule implementation. Your module doesn't define exports, as that is handled with attributes. I created a custom Attribute to export a View to a Region, and an infrastructure IModule that will register these views with their regions. For adding a Menu to your app, I think the best way would to be to export the Menu as a separate View. Then you'd have a Region that

Categories : Dotnet

Arquillian fails to inject dependencies after the first test class
I have a similar problem (the only difference is that I'm getting the message "WELD-001456 Argument resolvedBean must not be null"). Resolved beans are stored in an instance of the class org.jboss.weld.manager.BeanManagerImpl that is shared between all tests in micro deployment. In my case the cause of failure is that when some test finished, its thread is staying bound with old instance of TestRunnerAdaptor that is linked to the already cleaned bean manager (see method org.jboss.weld.manager.BeanManagerImpl.cleanup()). If some test from next micro deployment will use one of such threads it fail. The problem is related to Arquillian with version > 1.0.3.Final (in new versions field type org.jboss.arquillian.junit.State.lastCreatedRunner is changed from ThreadLocal to InheritableThreadLocal

Categories : Java

Can I use Ninject to inject dependencies into attributes rather than using the service locator pattern?
Attributes are created by the .NET Framework. So you can't do Constructor injection. The only two ways to inject into Attributes is to do PropertyInjection or ServiceLocation. PropertyInjection can be done like this: Add a IPlanningStrategy that does the scanning with reflection for your attribute (or ActionMethodSelectorAttribute). Return immediatly if not a controller. Foreach method that has this attribute add a IDirective that contains a reference to the MethodInfo Add A IActivationStrategy that injects the attribute using kernel.Inject(attribute). Best you have a look at the PropertyInjection implementation of Ninject it works exactly like this. It just needs some changes to do what you want.

Categories : Asp Net Mvc

Why do classes in the Python threading module expose factory functions instead of constructors?
There is no real advantage. Guido added the module 1998; the first revision already includes those factory functions. Perhaps he had plans for those factory functions, perhaps he was looking at the Java implementation and copied over some idioms, perhaps he wanted to make things pluggable with a C re-implementation in the back of his head. We can only guess, or ask Guido directly.

Categories : Python

BundleException: Unable to resolve module because it exports package 'org.slf4j.spi' and is also exposed to it from com.springsource.slf4j.api
SLF4J is OSGi friendly since a while so there is no need to use springsource based jar-s. Install the newest slf4j-api jar with the implementation you would like to use! How it works: slf4j-api uses classes that are not in the jar and they are not imported. slf4j-xxximpl (like slf4j-simple) are fragment bundles where the host is slf4j-api so they will have a common classloader. This means that you have to install an slf4j-api and slf4j-xxx together (if you install it runtime call a refresh on the container if necessary to have good wirings). This also means that slf4j cannot work with more implementations and it is also not a good idea to have multiple versions of slf4j-api in the same container. Solution: Remove the springsource based jar and install the newest slf4j-api and impl jar

Categories : Spring

How to Inject @Alternative with CDI from WAR into EJB Module
With the structure that you are describing, there is no way to obtain the desired injection. The EJB classloader will never be able to access the classes inside the WAR , hence the injection will never consider the alternative implementation. A solution is possible if you are willing to alterate the EAR structure, placing the alternative (D) in a lib/jar , along with the appropriare beans.xml. The D class will become visible to your EJB and to your WAR, and the injection shoul proceed as desired. EDIT The solution you posted, which I descibe here, is almost working. EAR - ejb-module-1.jar - A.class (@Inject I) - I.class - C.class (@Stateless implements I) - META-INF/beans.xml - ejb-module-2.jar - D.class (@Alternative @Stateless implements I) - META-

Categories : Java

Inject module dynamically, only if required
I haven't tried it as we have avoided large dependencies (thus far), but this article appears to show how to accomplish what you are wanting. http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx Good luck! -T

Categories : Angularjs

How to inject modules to main Angular app module on the fly
No, this is not officially supported at the moment. All the modules must be loaded in a browser (and declared as a dependency of a main application module) before AngularJS application is bootstrapped.

Categories : Angularjs

Guice: Inject a class bound by another module?
To be honest it sounds like this problem isn't actually one of Guice, but instead the standard problem across software engineering: ensuring your dependencies do what they claim to do. QueueModule shouldn't concern itself about whether DefaultCacheAdaptor holds up to its general contract. Instead, write a unit test for DefaultCacheAdaptor that guarantees that it bootstraps itself, then use it in QueueModule without a second thought. This is especially true because DefaultCacheAdaptor has a completely unrelated injector tree. You should be able to use DefaultCacheAdaptor opaquely, and stop concerning QueueAdaptor with its implementation details. Its bootstrapping is part of its implementation, not its API. Even if you were to merge the two Injector graphs into one (by injecting the Inject

Categories : Java

How to automatically inject helper classes in each new module?
I think I see what your dilemma is, but I have no good solution for it. However, since there are no other answers, I will contribute my two cents. I use the combination of a few strategies to help me with these kinds of problems: If the helper instance is truly module-specific, I let the module itself create and manage it inside. If I don't want the module to know about the creation or destruction of the helper(s), or if the lifetime of the helper instance is not tied to the module that is using it, or if I want to share a helper instance among several modules, I create it outside and pass the reference to the entry-point constructor of the module. Passing it to the constructor has the advantage of making the dependency explicit. If the number of the helpers are high (say more than 2-3

Categories : C++

How to inject parameters in enum constructor using Spring?
You cannot do this. In this official Java tutorial on Enum Types, it states Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself. Since an Enum is supposed to be a constant set of constants, it doesn't make sense to be able to create new ones, so the constructors are not available, even through reflection.

Categories : Java

multi module maven spring inject beans
You didn't presented your UI class. I suspect that UI is not a Spring managed bean, thus autowiring is off. Or your UI is annotated as Spring bean, but is created with new operator, not taken from Spring context. Well, if you made it as you explained, it must work. No mercy. I made a simple project https://github.com/michaldo/multi-module-vaadin-spring and it works

Categories : Spring

Inject callback from a class method defined in a module
Thanks @apneadiving, code is now : module MyModule extend ActiveSupport::Concern module ClassMethods def add_callback(options) foo = options.fetch(:foo) the_real_callback = -> do puts instance_exec(&foo) end before_save(the_real_callback) end end end class MyClass < ActiveRecord::Base include MyModule add_callback foo: -> { bar } def bar "bar" end end o = MyClass.new o.save # displays "bar"

Categories : Ruby On Rails

Explicitly accessing module var from module function in revealing module pattern
I want the function sayOhai to say "ohai" using the defined var. Assumed i do not want to change the parameter name of sayOhai, how can i access foo's value within sayOhai? You simply can't. The var foo is shadowed by the inner function parameter with the same name.

Categories : Javascript

Inject / Navigate RibbonTabItems depending on selected / loaded module
I had a similar problem and ended up keeping track of tabs added in a hashtable keyed by the module type name. The module tabs were developed in module views containing ribbon controls so the datacontext also needed to be transferred. Here is what I ended up with as my RibbonRegionAdapter (add your own namespace!): // Based on // http://www.codeproject.com/Articles/165370/Creating-View-Switching-Applications-with-Prism-4#AppendixA // with my modifications. /// <summary> /// Enables use of a Ribbon control as a Prism region. /// </summary> /// <remarks> See Developer's Guide to Microsoft Prism (Ver. 4), p. 189.</remarks> [Export] public class RibbonRegionAdapter : RegionAdapterBase<Ribbon> { private static readonly Hashtable RibbonTabs = new Hashtable();

Categories : C#

Spring Testing - Inject mocked bean with nested bean dependencies
You could use standalone mockMvc if you do want to unit test the controller. private MockMvc mockMvc; private SomeController controller = new SomeController(); @Mock private ResourceAdminService resourceAdminService; @Before public void setup() throws Exception { controller.setResourceAdminService(resourceAdminService); this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } If you still want to setup an ApplicationContext, but it's too annoying with the DI. Maybe you'll interested in this article(http://java.dzone.com/articles/how-use-mockstub-spring). But the Strategy C:Dynamic Injecting will rebuild an ApplicationContext per test which could slow you tests if you have too many @Test methods.

Categories : Java

expose a function in go package
Go Packages are not what you're perhaps thinking they are. Go programs are constructed by linking together packages. A package in turn is constructed from one or more source files that together declare constants, types, variables and functions belonging to the package and which are accessible in all files of the same package. Those elements may be exported and used in another package. It's not the same as e.g. #include etc.

Categories : Function



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.