express.Createserver() not working - javascript

I am beginner to nodejs. I tried below code. But server is not listening to the port and host.
var fs = require("fs");
var config = JSON.parse(fs.readFileSync("config.json"));
var host = config.host;
var port = config.port;
var express = require("express") ,http = require("http");
var app = express();
var server = http.createServer(app);
app.get("/", function(request, response){
response.send("hello");
});
app.listen(port, host);
I also tried below code. But found in SO that this method is deprecated. And I replaced it with above code. Though it is not working. I also tried installing express globally then also not listening to port. What might be the problem.
var express = require("express");
var app = express.createServer();
app.get('/', function(request, response){
response.send("hello");
});
app.listen(port, host);
This is my config file.
[{
"host" : "127.0.0.1",
"port" : 1337
}]

config is array not object, you need to access it accordingly(or change the config) .Here is corrected code;
var fs = require("fs");
var config = JSON.parse(fs.readFileSync("config.json"));
var host = config[0].host;
var port = config[0].port;
var express = require("express") ,http = require("http");
var app = express();
var server = http.createServer(app);
app.get("/", function(request, response){
response.send("hello");
});
var server = http.createServer(app);
app.get("/", function(request, response){
response.send("hello");
});
var server = app.listen(port, host);
server.on('error', function(err) {
console.log('error:' + err);
});
server.on('listening', function(){
console.log('server is up, all is well');
});

Related

socket.io application keeps loading

Why does my socket.io webapplication keeps loading, i've implemented auth with certifications, but when i try to access localhost, it keeps loading. ive tried follow this doc, but dosent help:https://socket.io/docs/v3/client-initialization/
i dont get any error.
server.s
'use strict';
// Setup basic express server
var express = require('express');
var app = express();
var port = process.env.PORT || 4000;
var crypto = require('crypto');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data/db.sqlite');
const bcrypt = require('bcrypt');
const tls = require('tls');
var validator = require('validator');
// Routing
app.use(express.static(__dirname + '/public'));
app.use(express.json());
// Chatroom
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
const fs = require("fs");
const server = require("https").createServer({
cert: fs.readFileSync("./server-cert.pem"),
key: fs.readFileSync("./server-key.pem")
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
const io = require("socket.io")(server);
io.on('connection', function (socket) {
console.log("works")
}
client.js
const fs = require("fs");
const socket = require("socket.io-client")(4000, {
ca: fs.readFileSync("./server-cert.pem")
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});

jaeger endpoint isnt recieving data using jaeger Node.js client

Was trying to connect to jaeger using HTTP request using nodejs but the spans are not reaching the jaeger endpoint. please help with this code snippet.,
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'servicename1',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
}
};
var options = {
tags: {
'servicename1': '1.0'
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Any help would be much appreciated!
Got it! We need to enable sampling strategy to reach the collector endpoint.
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'Jaeger_Service',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
},
'sampler': {
'type': 'const',
'param' : 0.1
}
};
var options = {
'logger': {
'info': function logInfo(msg) {
console.log('INFO ', msg)
},
'error': function logError(msg) {
console.log('ERROR', msg)
}
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
server.listen(8000);
console.log('Express server started on port %s', server.address().port);

not able to obtain socket connection to node server hosted on heroku

I am trying to send data from one node server to another node server. But when i host the one server on heroku i am not able to obtain a socket connection.
Hope anybody can help. Thanks in advance
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var value = "default";
var PORT = process.env.PORT || 3000;
// var engines = require('consolidate');
// app.set('views', __dirname + '/views');
// app.engine('html', engines.mustache);
// app.set('view engine', 'html');
var app = express();
//var server = app.listen(PORT, () => console.log(`Listening on ${
PORT }`));
var server = require('http').createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('+Client connected successfully+');
socket.on('data', function (data) {
console.log('data from pi' + data);
});
socket.on('disconnect', () => console.log('Client
disconnected'));
});
//console.log(PORT + 'actual listening to'+server.address().port);
server.listen(PORT);
client.js
var io = require('socket.io-client');
var socket = io.connect('https://herokuappname.herokuapp.com/', {
reconnect: true });
console.log('2');
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});

Node.js: Convert CSV to JSON and save it in a variable

So I'm having this code as a base and I have to use it to convert the content of "world_data.csv" to JSON.
I don't have a clue about how I can save that JSON in a variable. I guess the data I want is stored temporarly in "jsonArray", but how can I define a global variable which stores that data indefinetely?
var express = require('express');
var app = express();
var sys = require('util');
var path = require('path');
var bodyParser = require('body-parser');
var Converter = require("csvtojson").Converter;
app.use( bodyParser.json() );
app.use( express.static( path.join(__dirname, "public") ) );
var converter = new Converter({});
converter.on("end_parsed", function (jsonArray) {
console.log(jsonArray);
});
require("fs").createReadStream("world_data.csv").pipe(converter);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You need simply a global var. Plese read Javascript Closures
var express = require('express');
var app = express();
var sys = require('util');
var path = require('path');
var bodyParser = require('body-parser');
var Converter = require("csvtojson").Converter;
var jsonContent = {}; // <-- Your Global JSON Data
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
var converter = new Converter({});
converter.on("end_parsed", function(jsonArray) {
if (jsonArray) {
jsonContent = jsonArray
}
});
require("fs").createReadStream("world_data.csv").pipe(converter);
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Depends what you want with parsed result, for e.g pass it to the view:
app.get('/', function(req, res) {
require("fs").createReadStream("./world_data.csv").pipe(converter);
converter.on("end_parsed", function (json) {
res.json(json)
});
});
As csvtojson provides api and hooks you can call whatever you need on parsing process finish.
Or you can use oneliner that can be implemented as:
app.get('/', function(req, res) {
require("fs").createReadStream("./world_data.csv").pipe(new Converter({constructResult:false})).pipe(res)
})

How to get my node.js mocha test running?

I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this:
mocha test
I could not figure out how to get the reference to my app, routes.js:
var _ = require('underscore');
module.exports = function (app) {
app.post('/*', function (req, res) {
var schema={
type: Object,
"schema":
{
"totalRecords": {type:Number}
}
};
var isvalid = require('isvalid');
var validJson=true;
isvalid(req.body,schema
, function(err, validObj) {
if (!validObj) {
validJson = false;
}
handleRequest(validJson,res,err,req);
});
})
}
This is the server.js:
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
And finally test.js:
"use strict";
var request = require('supertest');
var assert = require('assert');
var express = require('express');
var app = express();
describe('testing filter', function() {
it('should return an error', function (done) {
request(app)
.post('/')
.send({"hh":"ss"})
.expect(400,{"error": "errormsg"})
.end(function (err, res) {
if (err) {
done(err);
} else {
done();
}
});
});
});
Create a separate file called app.js. The only purpose of this file would be to run the server. You'll also need to export your app object from server.js. So, your server.js would look like this
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
module.exports = app;
Create a new file called app.js and put this inside of it
var app = require('./app');
var port = process.env.port || 8000;
app.listen(port, function() {
console.log("App listening on port " + port);
});
Now, inside of your test file, import your app as follows
var request = require('supertest');
var assert = require('assert');
var app = require('./app.js');
....
Note that I assume all your files are in the same directory. If you've put your test file in a different folder then you'll need to give the right path while requiring your app object.

Categories