Piranha Piranha - 1 year ago 67
Node.js Question

How to export a value from a module?

This seems to be a simple problem, but the answers internet is cluttered with es5, babel, typescript, or legacy node 4 questions.

Question: How to export this:

class Server {

constructor(port) {
this._port = port;

start() {
// Some code here.

stop() {
// Some code here.

To use it app.js exactly like this:

var Server = require("server");

var server = new Server(80);

Pure Node 5 with ES6, no babel, or additional node packages. Just this.

Answer Source

You can export the class:

module.exports = Server;

And, if server.js is located in the same directory as app.js, you should use a relative path for require(), too:

// app.js
var Server = require("./server");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download