Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,819 answers

573 users

How to create, include and use your own module in Node.js

4 Answers

0 votes
// The module: datetime.js

exports.getDateTime = function () {
    return Date();
};
// The application: test.js

const http = require('http');
const dt = require('./datetime');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(dt.getDateTime());
  res.end();
}).listen(8080); 



// To run open http://localhost:8080/ in your web browser

/*
run:

Thu Feb 27 2020 17:11:54 GMT+0200 (GMT+02:00)

*/

 



answered Feb 27, 2020 by avibootz
edited Mar 1, 2020 by avibootz
0 votes
// The module: log.js

function log(s) {
    console.log(s);
}

module.exports = log;
// The application: app.js

const logm = require('./log')

logm('Node.js');

   
   
  
   
/*
run:
   
Node.js
   
*/

 



answered Mar 1, 2020 by avibootz
0 votes
// The module: worker.js

const worker = {
    name: 'Tom',
    age: 51
}

module.exports = worker;

// The application: index.js

const worker = require('./worker');

console.log(worker);
console.log(worker.name);
console.log(worker.age);


     
/*
run:
   
{ name: 'Tom', age: 51 }
Tom
51
 
*/

 



answered Mar 9, 2020 by avibootz
0 votes
// The module: worker.js

class Worker {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    show() {
        console.log(`name = ${this.name} age = ${this.age}`);
    }
}


module.exports = Worker;

 

// The application: index.js

const Worker = require('./worker');

const w = new Worker('Ivy', 37);


console.log(w);
w.show();
console.log(w.name);
console.log(w.age);


     
/*
run:
   
Worker { name: 'Ivy', age: 37 }
name = Ivy age = 37
Ivy
37

 
*/

 



answered Mar 9, 2020 by avibootz

Related questions

1 answer 135 views
135 views asked Dec 25, 2020 by avibootz
2 answers 215 views
1 answer 213 views
1 answer 341 views
1 answer 191 views
...