I do ES6 syntax in Node.js. As a starting point, I just tried to create a simple class that sets up and returns an Express server, but I'm not sure if this would be good or not in production.
I'm having problems accessing class member variables in other functions. Take a look at the code below:
import express from 'express'
import http from 'http'
const _server = null
const _app = null
class HttpServer {
constructor (port) {
this._port = port;
if (this._app === null) {
this._app = express()
}
if (this._server === null) {
this._server = http.createServer(this._app)
}
return this._server
}
start (callback) {
this._server.listen(this._port, (error) => {
return callback(error)
})
}
}
export default HttpServer
The constructor seems to work fine, although when I call the method start, I get an error that the variable this._serveris equal undefined. I thought the keyword thiswould be able to access the variables. I tried replacing the access method thiswith use HttpServer._server, but no luck. Any tips or advice would be appreciated!
, , , ES6!