Regarding this question: What is the purpose of Node.js module.exports and how do you use it?
I'm a Javascript beginner. In the referenced question...
mymodule.js code
var myFunc = function() { ... };
exports.myFunc = myFunc;
main js file
var m = require('./mymodule.js');
m.myFunc();
Is mymodule essentially a class file defining objects?
Node.js allows code to be separated into different modules. This modules are just javascript files that can expose functions or objects using the exports object.
There are more details of this convention
Nice documentation of the Node.js modules
There are no Classes in JavaScript but you can use patterns to emulate that behaviour. There is a question about implementing OOP patterns in JavaScript: what pattern to use when creating javascript class?
As a beginner there are very good books for JavaScript:
JavaScript: The Good Parts
JavaScript Patterns
They are short and will give you a very good insight of the JavaScript Language.
Is mymodule essentially a class file defining objects?
and functions, although in Javascript functions are objects, so the distinction may be moot.
Importantly, each module has its own scope, so any var declared therein will not be visible outside of the module.
The rest of your question about users and lists doesn't make sense as written. Javascript OO programming is a complete topic in its own right, and the module system doesn't really change that. Modules are just a way of wrapping code libraries.
Related
This question is about ES6 not about global variables.
When the new ES2015 export or export default were introduced. They were made so that you can import/get the same variables, values or items somewhere else using import. So I have a simple question. Why should we use export and import instead of just making a simple object of a class and getting items through it or just making static or global variables?
I know the fact that it can be used to make your code much cleaner and also to put the code easily into multiple files but let's just assume we have first.js and second.js and we have a variable called names in the first.js that we want to get in the second.js. Now you can either do that with import and export or by making an object in the second.js and accessing our variable by that object. So why is it better to use export and import?
export was introduced to be used alongside import (you need to explicitly declare what you need to later import), as part of the ES2015 module standard.
Before these standard modules were implemented, splitting up Javascript code into multiple files and not have all objects pollute the global object was only possible using sort short of non-standard module definition and/or module loaders like RequireJS. The simplest case was to wrap your code in Immediately Invoked Functions. ES6/2015 just standardize Javascipt modules.
Now you asked why not just have Javascript objects even in many files? The answer to that is namespacing
Actually - you make a good point.
namespace stuff is in C++. There are lots of people who think it is cool to have a namespace indicator in front of everything they use.
So, instead of saying { cout << my_string << endl; }, their whole program has { std::cout << my_string << std::endl; }.
Sometimes you see stuff like { disk::io::byte::bit::atom::neutron::quark::say_hi(2) }. And, the guy who wrote that thinks he's a super developer.
But, as they are purist, it more likely you will see { std::cout << myString << endl; } because camel case is so much more preferential than human readable strings.
Now, in node.js I am always doing something like const ClassFromMod = require('mod-with-class'). In the file, you have to say module.exports = ClassDeclaredInHere. I always do this, because really, is there any other way provided?
Or you can do this const {ClassFromMod} = require('mod-with-class').
Then you have to have, module.exports.ClassFromMod = ClassDeclaredInHere.
So, doing the same thing in the browser is sort of OK. But, now global contexts and local contexts are harder to work with - really. Just a little harder sharing things between modules when you have to. But, not to worry almost all of the time people partitions their modules just right. That's because they are people - in fact the sort of people who are more cautious than those in charge of nuclear reactors - because those people do some web programming. So, no Chernobyl when it comes to partitioning modules. Right?
Now, you can get your hands into a class def. And, the class is itself something of a namespace.
So, then why is there not a global registry of classes? Only that maybe different companies (individual developers) will use the same name for two remotely different classes. But, likely there would be some way around that.
One way might be to assign classes to uses (sort of name spacey). But, it might be more categorical. Like "engine" for something with a car feature, or "engine" for something that runs a script. Programming languages might have something like "talking about cars here". What would that be like?
start>> talking about cars <
let bval = engine.rev()
if ( bval ) {
<about scripts> engine.run("small program")
}
<<stop talking about car
That's an idea. Looking at it, I don' like it. It's sort of like "with" that lots of languages use.
So, with new strictures imposed on the programming environments, you get bugs and scope troubles that add to your long long long day. But, you should get that your question drawn from clear thinking is in some sense being steamrolled by a small group of people who can. And, you can take out the trash for them.
So, what about identifying objects by features and enabling sort of a flat namespace management? Could be driven by AI. Could have been done thirty years ago. But, now is now. But, the future exists for correcting the mistakes of the past.
Disclaimer: I’m a Node.js newbie.
There’s a number of class-based languages in which you can/must use namespaces to organize your code, for example: Java, PHP, ActionScript 3… For a number of those languages, if you choose/have to use namespaces, there’s generally a set of common practices and conventions that govern project organization then:
Classes form the basic code units, and responsibilities are spread across multiple classes.
The class file hierarchy reside in a single top-level directory (most of the time: src/ or lib/).
Each source file contains a single class definition and nothing else.
Each class resides at a specific level of a namespace (or package) hierarchy, which mirrors the filesystem; for example:
in Java: class com.badlogic.gdx.Application would be found in the src/com/badlogic/gdx/Application.java file
in PHP (with PSR-0): class Symfony\Component\HttpKernel\Kernel would be found in the src/Symfony/Component/HttpKernel/Kernel.php file
Foreign class symbols can be imported into the current scope via a specific statement:
in Java: import com.badlogic.gdx.Application;
in PHP: use Symfony\Component\HttpKernel\Kernel;
I’m used to this type of project organization, but I do realize that it’s specific to class/namespace-based languages and that it might not match JavaScript/Node.js’ usual idioms. If I understand the concept of Node.js modules correctly, it’s 1 source file = 1 module, but from what I’ve seen in a lot of NPM packages, a module usually export more than one symbol, and more often than not those exports are functions and not classes/constructors, so it’s pretty different from the conventions described above.
So, I have the following questions:
In JavaScript/Node.js, is it relevant at all to think about distribution of responsibilities in terms of «classes only» (using either the traditional constructor + prototype composition method or the new class shorthand)?
Is the type of project organization described above possible at all in the context of a Node.js project?
In JavaScript/Node.js, is it relevant at all to think about distribution of responsibilities in terms of «classes only» (or «prototypes only» for that matter)?
In Javascript it's a choice rather than a mandate. You can go full OOP even file structure wise. Or just write modules as pure functions. I'd advise you to stick to the structure that's easier for others, who may want to understand your code, to follow. For example, the OOP style:
Let namespace be the path under src
/src/org/xml/XMLDocument.js
and have a class very similar to the popular OOP languages:
// imports
const fs = require('fs');
const XMLNode = require('./XMLNode');
// class def
class XMLDocument extends XMLNode {
// constructor
constructor(filePath){
...
}
// property getter
get filePath(){
...
}
// method
function getElementsByName(name){
...
}
}
// export class to outer world
module.exports = XMLDocument;
Use the class
// import
const XMLDocument = require('./org/xml/XMLDocument');
// create an instance
const doc = new XMLDocument('./mydoc.xml');
So yes, following an OOP structure is relevant when you tackle the problem the OOP way. And there are alternate ways as well.
Another "creator" oriented custom style:
function createXMLDocument(filePath){
const doc = {};
doc._type = "XMLDocument";
... // make the object have XMLDocument features
return doc;
}
function createDXMLDocument(filePath){
const doc = cerateXMLDocument(filePath);
doc._type = "DXMLDocument";
... // modify parent object with DXML features
return doc;
}
You see, there are some patterns the developer adheres to and write all project code in that style.
Is the type of project organization described above possible at all in the context of a Node.js project?
A Node.js project can have any kind of code organisation because of certain features:
Javascript module system is nothing but referencing a js file present somewhere in file system. So there are no special restrictions on file placement. There are modules that are built in, or can be installed via npm.
Module exports can export one or multiple "things" to external world. So a lot of flexibility here as well.
Javascript itself can be easily written in many styles, functional, OOP, procedural etc. It allows developer to modify a lot of Javascript's own nature. Hence possibly "mimic" many programming styles.
In JavaScript/Node.js, is it relevant at all to think about distribution of responsibilities in terms of «classes only» (or «prototypes only» for that matter)?
To be honest I don't really understand this question. You should follow OOP principles if you use classes, but if you do not, you still need to find cohesion between your functions and organize them in modules and folders based on that.
Is the type of code organization described above usual or relevant at all in the context of a Node.js project, and is it technically implementable without too much trouble?
Javascript modules don't have namespaces, which make things a bit easier (Remember that C# and c++ projects usually have a folder structure totally different than the namespaces). Use folders as namespaces and you'll be fine. There is no such rule that you can only have one class per source file. I usually start writing classes and functions in a single file, and reorganize into multiple files when the file grows big. JavaScript's module system is very flexible, you can organize the code literally any way you want.
If not, what are the traditional ways of handling repartition of responsibilities and code reuse in a Node.js project?
The same as anywhere else.
I am learning design pattern in JavaScript, and I'm going to use the module pattern. I'm puzzled with two things.
1 - If I would create a plugin, then I can use the module pattern, and have private and public methods/variables. But if I have a full JavaScript file, I don't need private and public methods, since one part of the program has nothing to do with another part. So what's the point of private and public methods?
2 - Since the JavaScript file is really long, should I have nested module's? How should I go about a full file of JavaScript?
JavaScript has moved on. ES6--which there is no real reason not to move up to, if you haven't already--has its own modules. So there is no need to "simulate" modules with old patterns. Example:
// Old style.
var myModule = function() {
var privateVar;
function getPrivateVar() { return privateVar; }
return {getPrivateVar: getPrivateVar};
}();
console.log(myModule.getPrivateVar());
// New style.
let privateVar;
function getPrivateVar() { return privateVar; }
export {privateVar};
// Using it
import {getPrivateVar} from './myModule';
console.log(getPrivateVar());
In the above, privateVar is by definition private to the module (file). There's no need to keep it private by wrapping it in an IIFE. Instead of handling the exports ourselves as properties of a single returned object, we use the ES6 export mechanism to export it explicitly.
(1)
When all Javascript files are loaded, all the scripts in all files are just like they are in one file. Script in one file can access (read, update, delete) global variables in other files. There are a lot of questions on this, you can easily search for those.
Of course, "one part of the program has nothing to do with another part", but in case you are in team with many members, each works on a part of the system (or in some cases, a file). Then, there is a chance that one person accidentally changes variables created by another person. Those kinds of error are quite easy to detect. But if you can modularize you script, you can avoid those kinds of error altogether.
(2)
You can go slow. While writing code to complete requirements, try to recognize the parts of code that can be separated to a modules (or even nested modules). Them put them into other files.
You should be creative and careful while doing so. The code might grow very fast and things get out of control very quickly.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return all of the functions that are defined in a Javascript file
OK so i have a JS file in which i have a number of JavaScript functions defined.Is there any way to parse out the name of all function in that particular JS file using JavaScript.Any guidance or link to achieve this will be appreciated
If you are not generating the js file dynamically, the easiest and safest option is to keep a hard-coded list of function names.
All other parsing methods are risky because
String parsing of the code is not safe, since you will have to cater
too many cases
There are options to get all global functions. But they are browser
dependent. like looping through all window objects for objects with typeof window[x] === 'function'
If it's just for development purposes then use an IDE. The IDE will depend on your environment. For example, you might you IntelliJ if your server side code is Java or Visual Studio's if you are a .NET shop.
If you really need to use javascript to dynamically go through the list of functions I suggest rethinking why you need to do it. If it turns out usefull you could namespace your functions and then just iterate over the namespace functions. See this answer for how to namespace https://stackoverflow.com/a/5947280/695461. Then iterate over the "public" functions.
Again, if it's just for development ease of use, use an IDE. They have whole teams of people writing parsers and syntax highlighters and structure diagrams for you.
I have a general question about the design of JavaScript Libraries.
I am trying to consolidate common methods into one js file so they can be reused by different scripts.
I have taken a look at how the JSON library is structured and believe it was a good approach.
JSON for Javascript.
So they start off creating an instance of the class:
if (!this.JSON) {
this.JSON = {};
}
Then they do this:
(function () {
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
This is works perfect if you just want to do JSON.[function_name], but what if I want to have a more structured library such that I want: JSON.[subgroup].[function]. How would I structure my JS library in such a way?
Any links to resources are greatly appreciated, thanks.
I would recommend you to follow the Module Pattern in JavaScript instead of following JSON's pattern strictly. Your subgroup is actually referring to sub-modules. Take a look at the following excellent article:
Ben Cherry's JavaScript Module Pattern In-Depth
Other resources you should probably go through:
John Resig's Learning Advanced JavaScript
Seven JavaScript Things I Wish I Knew Much Earlier In My Career
The Seven Deadly Sins Of JavaScript Implementation
There are problems with the module pattern. See http://snook.ca/archives/javascript/no-love-for-module-pattern. I used to use it before but stopped. Now I just tend to keep it simple. If you really want sub-namespacing you can make a simple namespace function for the job.
See
http://blogger.ziesemer.com/2008/05/javascript-namespace-function.html