Say I have one .js file containing a javascript object. I want to be able to access that object and all of its functionality from another .js file in the same directory. Can I simply export this object with the module.exports object and require() it in the other .js file? If this is possible can you give me an example?
If it helps I'm developing with node.
This is the way I create modules:
myModule.js
var MyObject = function() {
// This is private because it is not being return
var _privateFunction = function(param1, param2) {
...
return;
}
var function1 = function(param1, callback) {
...
callback(err, results);
}
var function2 = function(param1, param2, callback) {
...
callback(err, results);
}
return {
function1: function1
,function2: function2
}
}();
module.exports = MyObject;
And to use this module in another JS file, you can simply use require and use your object as normal:
someFile.js
var myObject = require('myModule');
myObject.function1(param1, function(err, result) {
...
});
Of course you can. In my example I use obj to hold my config info. I put it in a file called index.js in config folder. This makes the index the preferred choice to be picked when I import 'config'. I have 2 exports here one for my node and api stuff and the other for my db. You can ignore the first bit where I set the environment.
const environment = {
development: {
isProduction: false
},
production: {
isProduction: true
}
}[ process.env.NODE_ENV || 'development' ];
export default Object.assign({
host: 'localhost',
port: '3000',
remoteApi: {
token: {
'X-Token': '222222222222222222'
},
base: 'https://www.somedomain.com/api'
}
}, environment);
export const db = {
dbHost: 'localhost',
dbPort: 176178
};
Calling import config from '../config'; will pick the default one. And if I specify I can get the db export import { db } from '../config';
In one file:
module.exports.myObj = some object...;
In the other:
Obj = require('myFile.js').myObj;
Everything in a js file on node is local to that file unless you put it in the export object. This actually is very different from JavaScript in a browser--in the browser all files that get imported act together like one big file.
You can kinda think about node files as though you are creating a module object and passing it' into a function surrounding your code.
module = { 'exports' : {} };
(function(module){
//your js file
...
})(module)
the simplest approach, in my opinion:
write Person.js: (note it comes with ctor)
module.exports = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function () {
return this.firstName + ' ' + this.lastName;
}
}
and consume it:
var person = require('./Person.js');
var person1 = new person('James', 'Bond');
console.log(person1.fullName());
note that in this simple solution all methods are "public".
ref: https://www.tutorialsteacher.com/nodejs/nodejs-module-exports
as per es6 :-
const person = function(name){
console.log(`Name of the person is ${name}`);
}
export default person;
You can export object like
modules.js
export const events = {};
events.click = function (param1, param2...) {
//do something here
}
events.change = function (param1, param2...) {
//do something here
}
events.get = function (key, response) {
//do something here
response({status: "success"})
}
In main.js
import {events} from "./modules"
console.log(events)
Now you can use the Objects
events.get("my_key", (resp) => {
console.log(resp) // {status: "success"}
})
Related
I've been stuck on this issue for a while. I cannot describe it accurately enough to find solutions online - apologies if it is a duplicate question.
I want to access helloWorld() from module.js:
export function HelperProvider() {
return class Helper {
constructor() {
}
helloWorld() {
console.log('Hello World');
}
}
}
In another file:
import { HelperProvider } from 'module.js'
const helperProvider = HelperProvider;
const helper = new helperProvider();
helper.helloWorld();
However, I encounter the following error:
Uncaught TypeError: helper.helloWorld is not a function
Any help would be very much appreciated.
You need to invoke the function HelperProvider to get the class.
const helperProvider = HelperProvider();
function HelperProvider() {
return class Helper {
constructor() {
}
helloWorld() {
console.log('Hello World');
}
}
}
const helperProvider = HelperProvider();
const helper = new helperProvider();
helper.helloWorld();
You are using module features that's not out of the box in nodejs, if you want to use modules you'll need to set type: "module" in the package.json file... see details
If you wanna use node ways:
module.js
function HelperProvider() {
return class Helper {
constructor() {}
helloWorld() {
console.log("Hello World");
}
};
}
module.exports = HelperProvider;
index.js
const HelperProvider = require("./Helper");
const helperProvider = HelperProvider();
const helper = new helperProvider();
helper.helloWorld();
If you want pass parameters into module you do it like this:
index.js
let test = require("./module.js")(something);
module.js
module.exports = (something) => {
//Working with `something` here
};
But is there so way how to do it without using module.exports = (var) => {}?
More specifficaly to be able to write for example code outside function container and then at the end of file do module.exports?
Or you are able to just do this?
const globalSomething;
(something) => {
globalSomething = something;
}
module.exports = heavyWorkWith(globalSomething);
If you understand me.
You aren't restricted to an unnamed function to pass around parameters, you can use a named function
export default function myExport(something) {
//...
}
or even a class
export default class myExport() {
constructor(something) {
//...
}
}
And on the inverse side, import:
const myExport = require('./myModuleOrWhatever');
const foo = new myExport(something);
Even moreso, you can just pass along module constants with your anonymous module export
const bar = somethingElse;
const baz = moreElse;
/*
alernatively
export default const bar = somethingElse
*/
module.exports = {
foo: (something) => {
//Working with `something` here
},
bar,
baz,
};
Dear all I just started learning modules in javascript. This is my implementation of a module:
module.exports = function(logger_level) {
this.info = function(message) {
stdout(message);
};
};
function stdout(message)
{
process.stdout.write(message+'\n');
}
and I have to invoke it like this:
var logger = require('./js/logger.js');
var logger1 = new logger("info1");
logger1.info("info");
My question is how to change my implementation of the module so that I could invoke it like this:
var logger = require('./js/logger.js')("info");
logger.info("info");
If you want to use it like that, there's no need for a constructor function at all:
module.exports = {
info: function(message) {
stdout(message);
}
};
function stdout(message)
{
process.stdout.write(message+'\n');
}
I just started learning modules in javascript.
Note that this isn't "modules in JavaScript" so much as it is "modules in NodeJS". JavaScript's modules, which weren't introduced until ES2015 ("ES6"), look and act quite different, but they aren't broadly-supported yet. When they are, your module might look like this:
// ES2015+ syntax
export default {
info: function(message) {
stdout(message);
}
};
function stdout(message)
{
process.stdout.write(message+'\n');
}
...and used like this:
import logger from './logger.js';
logger.info("info");
You're looking for a factory function. Applying it to your use case it would look like:
module.exports = function(logger_level) {
return {
info: function(message) {
stdout(message);
}
};
};
function stdout(message)
{
process.stdout.write(message+'\n');
}
You can wrap your constructor function with an object and return an instance of your constructor function
module.exports = {
return new function(logger_level) {
this.info = function(message) {
stdout(message);
};
};
}
And call it
var logger = require('./js/logger.js');
logger.info("info");
You can also make a singleton pattern to work with a single instance of your constructor function
I need to access to a variable that i define in my index.js from static.js which is called with require()
Index.js
function API() {
var self = this
self.init = function(apikey, region, locale) {
//Some stuff
self.region = region
self.locale = locale
self.apikey = apikey
self.static = require('./static').static
}
}
module.exports = new API();
Static.js
module.exports = {
static: {
someFunction: function(someParameters) {
//Need to access to self.region, self.locale and self.apikey
},
otherFunction: function(someParameters) {
//Need to access to self.region, self.locale and self.apikey
}
}
My problem is to use region, locale and apikey from the static.js file
Test.js
var api = require('./index.js');
api.init('myKey', 'euw', 'en_US')
console.log(api);
does that:
RiotAPI {
region: 'euw',
locale: 'en_US',
apikey: 'myKey',
static: { someFunction: [Function], otherFunction: [Function] }
}
which is okay but when i call someFunction() with the good arguments it tells me that self.region (and the others i guess) is not defined
You need to put the methods from static.js at the top-level of your API instance.
var static = require('./static').static
function API() {
// constructor
}
API.prototype.init = function(apikey, region, locale) {
//Some stuff
this.region = region
this.locale = locale
this.apikey = apiKey
}
Object.assign(API.prototype, static)
module.exports = new API();
Then reference this.region etc. in your static methods.
I know that all javascript is valid typescript but I'd like to start converting my javascript to typescript conventions. I'm battling this one snippet of JS:
My standard Javascript that works
if (MyCompany === undefined) {
var MyCompany = {};
}
MyCompany.Uploader = MyCompany.Uploader || {};
MyCompany.Uploader.Core = function (config) {
'use strict';
function build() {
console.log("building");
}
return {
build: build
};
};
var config = {this: "that};
MyCompany.Uploader.Core(config).build(); // outputs building to console
I've been messing with multiple approaches and I feel like I not close enough.
My failed attempt at converting to Typescript
namespace MyCompany.Uploader {
export var Core = (config:any) => {
function build() {
console.log("building");
}
};
}
let configobj = {here:"there"};
MyCompany.Uploader.Core(configobj).build();
This simply doesn't work. I can't seem to access the build function. I'm sure this is a rookie mistake.
The error I get: Property build does not exist on type void
That's because you did not add an important part of your javascript code into the typescript version, and that's the return object which contains the reference for the build function, it should be:
namespace MyCompany.Uploader {
export var Core = (config: any) {
function build() {
console.log("building");
}
return {
build: build
}
};
}
let configobj = { here: "there" };
MyCompany.Uploader.Core(configobj).build();
You can also define interfaces for the config and the return object:
namespace MyCompany.Uploader {
export interface Config {
here: string;
}
export interface Builder {
build: () => void;
}
export var Core = (config: Config): Builder => {
function build() {
console.log(config.here);
}
return {
build: build
}
};
}
let configobj = { here: "there" };
MyCompany.Uploader.Core(configobj).build();