Error: socket hang up code: 'ECONNRESET' in Node.js - javascript

I am trying to post files using HTTP request on Node.js ,but after some files posted then it randomly shows
[Error: socket hang up] code: 'ECONNRESET'
My code for file sending is,
var http = require('http');
var request = require('request');
var fs= require('fs');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
var serverUrl='http://localhost:3000';
function uploadFile(){
var req = request.post(serverUrl+'/api/file/upload', function (err, resp, body) {
if (err) {
console.log(err);
} else {
console.log(body);
}
});
var form = req.form();
form.append('file', fs.createReadStream('abcd.mp3'));
}
uploadFile();
server.listen(8000);

Related

How can I send command line output through node.js server-sent-event and show it in browser

I am relatively new to JavaScript and I'm setting up a server sent event (sse) with node.js using some examples I see in the internet. My question is how can I send the output of the lsExample() command line function throught the res.write() function to show it in the browser.
var SSE = require('sse')
, http = require('http');
//var exec = require('child_process').exec;
var child;
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(here);
res.end('okay');
});
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function lsExample() {
const { stdout, stderr } = await exec('ls');
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
lsExample();
server.listen(8080, '127.0.0.1', function() {
var sse = new SSE(server);
sse.on('connection', function(client) {
client.send('hi there!');
});
});
Is it possible?
var http = require('http');
var SSE = require('sse');
//var exec = require('child_process').exec;
var child;
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
lsExample().then( (result)=>{
res.write(JSON.stringify(result));
res.end('');
},(err)=> {
res.write("error");
res.end('');
});
});
const util = require('util');
const exec = util.promisify(require('child_process').exec);
function lsExample() {
return new Promise(async function(resolve, reject) {
try {
const { stdout, stderr } = await exec('ls');
resolve({ "stdout" : stdout, "stderr" : stderr});
} catch (err){
reject(err);
}
});
}
server.listen(8080, '127.0.0.1', function() {
var sse = new SSE(server);
sse.on('connection', function(client) {
client.send('hi there!');
});
});

Consuming restfull api and share the result to web page using Node.js

I am trying to request data from RESTful API and sharing the result to html web page using Node.js. My code runs well, but I want to make this RESTful request every time I call the webpage not just when I run a Node.js server.
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var request = require("request");
var temp = "";
var options = { method: 'GET',
url: 'My_URL',
headers: { authorization: 'Basic My_Autho' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
temp = body;
console.log(body);
});
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'
});
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var renderedHtml = ejs.render(content, {temp: temp});
res.end(renderedHtml);
});
}).listen(8000);
Maybe you could move your call to the external REST api inside the request handler ?
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var request = require("request");
var temp = "";
var options = { method: 'GET',
url: 'My_URL',
headers: { authorization: 'Basic My_Autho' }
};
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
request(options, function (error, response, body) {
if (error) throw new Error(error);
temp = body;
console.log(body);
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var renderedHtml = ejs.render(content, {temp: temp});
res.end(renderedHtml);
});
});
}).listen(8000);

Node how to pass file to http.write method?

I woudl like to print file to res.write() method but I get error:
TypeError: First argument must be a string or Buffer
My code:
var fs = require("fs");
var http = require("http");
http.createServer(function (req, res){
res.write(getData());
res.end();
}).listen(3333);
function getData(){
fs.readFile('testfs.txt', function(err, data){
if(err)
{
console.log("Error: " + err);
}else {
console.log(data.toString());
return data.toString();
}
});
}
What's the problem?
res.write didn't get string nor buffer because your function getData wasn't asynchronous. Here's the fix I hope will solve your problem:
http.createServer(function (req, res){
getData(function(data){
res.write(data);
res.end();
}));
}).listen(3333);
function getData(cb){
fs.readFile('testfs.txt', function(err, data){
if(err)
{
console.log("Error: " + err);
}else {
cb(data.toString());
}
});
}
Where cb argument is a callback function obviously.
Alternatively, you can use streams:
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
fs.createReadStream('testfs.txt')
.on('error', (e) => {
console.log('Error:', e);
res.statusCode = 500;
res.end();
})
.pipe(res)
}).listen(3333);
Do it the other way around; just call getData and pass in response, then when the file is loaded, call response.end(string).

Node js displaying images from server

I am trying to display an image on a basic web page on a localhost w/ port 5000
here is main.js
var http = require('http');
var domain = require('domain');
var root = require('./root');
var image = require('./image');
function replyError(res) {
try {
res.writeHead(500);
res.end('Server error.');
} catch (err) {
console.error('Error sending response with code 500.');
}
};
function replyNotFound(res) {
res.writeHead(404);
res.end('not found');
}
function handleRequest(req, res) {
console.log('Handling request for ' + req.url);
if (req.url === '/') {
root.handle(req, res);
} else if (req.url === '/image.png'){
image.handle(req, res);
} else {
replyNotFound(res);
}
}
var server = http.createServer();
server.on('request', function(req, res) {
var d = domain.create();
d.on('error', function(err) {
console.error(req.url, err.message);
replyError(res);
});
d.run(function() { handleRequest(req, res); });
});
function CallbackToInit(){
server.listen(5000);
};
root.init(CallbackToInit);
Using callbacks I want the server to start listening(5000) only after the init function of the following code runs
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(body);
};
exports.init = function(cb) {
require('fs').readFile('image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}
It's an assignment I can't use express
I am trying to get image.png to be displayed, I think body = data doesn't work because it can't hold an image like a string? I don't want to put any HTML into my js file.
Don't roll your own app server. Use one of the great web app frameworks like express or connect.
var express = require('express');
var app = express();
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 5000);
Trust me, this is better.
Take a look at the node.js example for a simple http server or a tutorial/example, such as this, for serving static files through a simple server.

client server communication using node.js

In my client machine i have the following code
client.js
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var exec = require('child_process').exec;
var server = http.createServer(function(req, res) {
switch(req.url) {
case '/vm/list':
getVms(function(vmData) {
res.end(JSON.stringify(vmData));
});
break;
case '/vm/start':
req.on('data', function(data) {
console.log(data.toString())
exec('CALL Hello.exe', function(err, data) {
console.log(err)
console.log(data.toString())
res.end('');
});
});
break;
}
});
server.listen(9090);
console.log("Server running on the port 9090");
in my server side machine am using following helper.js
var options = {
host: '172.16.2.51',
port: 9090,
path: '/vm/start',
method: 'POST'
};
var req = http.request(options, function(res) {
res.on('data', function(d) {
console.log(d.toString());
});
});
req.on('error', function(e) {
console.error(e);
});
req.end('');
while running node helper.js am getting { [Error: socket hang up] code: 'ECONNRESET' }
it doesn’t print data.tostring() contained in the client side.
Try adding res.writeHead(200); before your switch statement.
This method must only be called once on a message and it must be called before response.end() is called.
From http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers.
Update
After our discussion the following client.js works:
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var exec = require('child_process').exec;
var server = http.createServer(function(req, res) {
switch(req.url) {
res.writeHead(200);
case '/vm/list':
getVms(function(vmData) {
res.end(JSON.stringify(vmData));
});
break;
case '/vm/start':
req.on('data', function(data) {
console.log(data.toString())
exec('CALL Hello.exe', function(err, data) {
console.log(err)
console.log(data.toString())
});
});
req.on('end', function() {
res.end('');
});
break;
}
});
server.listen(9090);
console.log("Server running on the port 9090");

Categories