Here is the thing :
I want to create an simple API Server, request from user being parsed and translated to simple socket message that transmitted to the socket server.
Here is the code
The Express Server :
var express = require('express');
var app = express(),
handler = require('./lib/urlparser.js');
app.get('/', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
app.get('/:command/:mode/:addr/:value', handler.handleRequest);
app.listen(80);
console.log('Listening on port 80...');
And the handleRequest module
exports.handleRequest = function(req, res) {
var net = require('net');
var HOST = '192.168.1.254';
var PORT = 8888;
var client = new net.Socket();
/* translate the url params and save it to var request and send it */
/* The code goes here */
client.connect(PORT, HOST, function() {
//console.log('Connected To: ' + HOST + ':' + PORT);
client.setEncoding('utf-8');
client.write(request);
//console.log('Message Sent');
});
client.on('data', function(val) {
//console.log('The Data: ' + val);
res.send([{addr:'test'}, {value: val}]);
client.destroy();
});
client.on('close', function() {
//console.log('Connection closed');
});
};
This code works, I just need to know is it correct or is there any way to include the net module and declare the ip and port of the socket server inside the main js file(outside the module?
Any help would be appreciated.
You can definitely move the code from the module to the main file.
First, in the main file, create a function named handleRequest that takes the same variables and has the same body as the function in the handleRequest module. That is,
var handleRequest = function(req,res){
var net = require('net')
...
...
}
Second, change this line:
app.get('/:command/:mode/:addr/:value', handler.handleRequest);
into this:
app.get('/:command/:mode/:addr/:value', handleRequest);
Now you no longer to need to include the module. Good luck!