JSON.stringify gets very slow when it stringify a string to json - node.js

I just get started learning some JavaScript and I encountered a strange problem when I use JSON.stringify to convert a string into json format. It got very slow and evantually produced a wrong result(not <"what ever in the string">). At the point where it happens, the source of the string is actually a TCP connection(to a java program). Here is the code I used.
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'application/json'});
var net = require('net');
var client = new net.Socket();
client.connect(3344,'192.168.1.4',function(){
......
}
client.on('data', function(result){
......
response.write(JSON.stringify(result));
......
response.end();
});
client.on('error', function(ex) {
var error = "error code: "+ex.code;
response.write(JSON.stringify(error));
response.end();
}
});
(Result is a plain text that has nothing to do with JSON)
when it executed to "response.write(JSON.stringify(result));", it almost stopped there for a minute and gave me a wrong result. However, the "response.write(JSON.stringify(error));" down below works complete fine. So I change the code a little bit to:
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'application/json'});
var net = require('net');
var client = new net.Socket();
client.connect(3344,'192.168.1.4',function(){
......
}
client.on('data', function(result){
......
var result2 = result+' ';
response.write(JSON.stringify(result2));
......
response.end();
});
client.on('error', function(ex) {
var error = "error code: "+ex.code;
response.write(JSON.stringify(error));
response.end();
}
});
Then there is no problem at all.
I suppose there are some problem with the character encoding? Does anyone know why it behaves like this?

var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'application/json'});
var net = require('net');
var client = new net.Socket();
client.connect(3344,'192.168.1.4',function(){
......
}
client.on('data', function(result){
......
response.write(result);
//response.write({"data":result});
......
response.end();
});
client.on('error', function(ex) {
var error = "error code: "+ex.code;
response.write(error);
//response.write({"error code":ex.code});
response.end();
}
});

Related

Node js undefined printed using fs.appendFile

I have just started out learning Node js. I can't understand why in output.txt I am seeing "2020 Septemberundefined undefined" in output.txt when I call:
http://localhost/?month=September&year=2020
I am expecting to see just "2020 September" in output.txt.
var http = require('http');
var url = require('url');
var fs = require('fs');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
fs.appendFile('output.txt', txt, function (err) {
// nothing
});
res.end(); //end the respons
}).listen(8080); //the server object listens on port 8080
The favorite icon. Add console.log(req.url). You will see that the browser makes two requests.
Browser is sending requests for http://localhost:8080/favicon.ico, behind the scenes.
So whenever you hit http://localhost:8080/?month=September&year=2020,
node write "2020 September" to output.txt file, meanwhile browser hit favicon.ico request then node write again "undefined undefined" in output.txt file.
if you want to skip favicon.ico request,
var http = require('http');
var url = require('url');
var fs = require('fs');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
if (req.url != '/favicon.ico') {
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
fs.appendFile('output.txt', txt, function (err) {
// nothing
});
}
res.end(); //end the respons
}).listen(8080);

Want to write capture and re-transmit http/https request to Browser?

I want to write a simple Node Js application which will capture and re-transmit http/https request to Browser?
I have written the below code, but it works only for http request.
var server = http.createServer(function (req,res) {
console.log("start request:", req.url);
var option = url.parse(req.url);
option.headers = req.headers;
var proxyrequest = http.request(option, function (proxyresponce) {
proxyresponce.on('data', function (chunk) {
console.log("proxy responce length" ,chunk.length);
res.write(chunk,'binary');
});
proxyresponce.on('end',function () {
console.log("proxy responce ended");
res.end();
});
res.writeHead(proxyresponce.statusCode, proxyresponce.headers);
});
});

To parse the query string not working

Im self-educating Node.js. I have created two simple HTML files (summer.html and winter.html) and noded the JS on node.js. I went on localhost:5354/summer.html (and winter.html). Nothing is showing up and I got an error message
This site can’t be reached
The connection was reset.
Try:
Checking the connection
Checking the proxy and the firewall
Running Windows Network Diagnostics
ERR_CONNECTION_RESET
I have tested other lessons and was able to display results on localhost:5354/ but this one doesnt work. What did I do wrong?
JS
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(5343);
Hit this URL
localhost:5343/summer.html
Because, You listen in 5343 PORT. But you hit 5354 Port

Sending a single-packet HTTP response in Node.js

To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:
var fs = require('fs');
var http = require('http');
var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);
Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?
var http = require('http');
var fs = require('fs');
var file = process.argv[2];
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html;"});
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
response.write(html);
response.end();
});
}).listen(8000);
the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.
I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.
try using something like-
var file = process.argv[2];
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});

error in node.js TypeError: Object #<Object> has no method 'createserver' at Object.<anonymous> (/home/aashish/chatbox/main.js:5:16)

i am facing some error in developing chat server client on linux please help
var http = require('http');
fs =require('fs');
var app = http.createserver(function (request, response)
{
enter code herefs.readfile("client.html",utf-8,function(error,data)
{
response.writehead(200,{'content-type': 'text/html'});
response.write(data);
response.end();
})
}).listen(1337);
io.sockets.on('connection',function(socket)
{
socket.on('message_to_server',function(data)
{
io.socket.emit("message_to_client",{message: data["message"]});
});
});
// at Object. (/home/aashish/chatbox/main.js:5:16)
error
it's createServer where S is an uppercase letter
createServer() is now deprecated meanwhile you could use Server() instead .. just check the following snippet or simply use express web framework.
var http = require("http");
var server = http.Server(function(request, response) {
response.end("heeloo world");
});
server.listen(3030, function(err){
if(!err)
console.log("success");
else
console.log("error");
});

Resources