>npm init
//my-number.js //module class MyNumber { constructor(aNumber) { this.n = aNumber; } square() { return this.n * this.n; } cube() { return this.square() * this.n; } toString() { return `MyNumber(${this.n})`; } } //------------------------------------------ exports.MyNumber = MyNumber;
//module-user1.js const tools =1require('./my-number'), prn = (o) => console.log(o.toString()); let myNum = new2tools.MyNumber(3); prn(myNum); prn("Square: " + myNum.square()); prn("Cube: " + myNum.cube());
>node module-user1 MyNumber(3) Square: 9 Cube: 27
//tools.js const capitalize = (string) => { //Capitalized and return param. return string.charAt(0).toUpperCase() + string.slice(1); } const camelCaseToLabel = (camelCaseString) => { //'bestOperaSong' = 'Best Opera Song' const str = capitalize(camelCaseString); return str.replace(/([a-z])([A-Z])/g, '$1 $2'); } //------------------------------------------ exports.capitalize = capitalize; exports.camelCaseToLabel = camelCaseToLabel;
//module-user2.js //"." for current (this) directory const tools =1require('./tools'); const name = 'asha'; console.log(`name: ${name}`); console.log(`name (capitalized): ${2tools.capitalize(name)}`); const varName = 'bestOperaSong'; console.log(`\nName: ${varName}`); console.log(`Label: ${3tools.camelCaseToLabel(varName)}`);
>node module-user2 name: asha name (capitalized): Asha Name: bestOperaSong Label: Best Opera Song