Error: read ECONNRESET on native node.js http - javascript

Having an issue. No modules except native http and fs:
var server = http.createServer((req, res) => {
res.on("clientError", err => {console.log(err.stack);});
if (req.url == "/index.js") {
fs.readFile("./index.js", (err, data) => {
if (err) throw err;
res.end(data);
});
} else {
fs.readFile("./index.html", (err, data) => {
if (err) throw err;
res.end(data);
});
}
}).listen(8080);
Error:
events.js:160
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:1020:11)
at TCP.onread (net.js:568:26)
On the first load, everything is served properly
On reload, it serves the HTML file and then throws that error.
my js file, which uses websocket connections, isn't served, so I don't think that that's the part of the code that's erroring
If you're interested in seeing the full code, you can find it on my github (it's a connect four game)

Related

fs Error: EISDIR: illegal operation on a directory, read

I'm getting "Error: EISDIR: illegal operation on a directory, read" after trying to read the content of a .json. This is how I'm trying to access the file. I'm using the FileSystem of node js.
fs.readFile( path, ( err, fileData) => {
if (err) {
throw err;
}
else {
return fileData;
}
});
While debugging I can see that the error is thrown before the if statement.
Any idea?
Maybe the path to the file is not the right one, make sure the path of your file looks like the one that appears in the following code:
const fs = require('fs');
fs.readFile('PATH_TO_YOUR_FILE/File_Name.json', (err, fileData) => {
if (err) {
throw err;
} else {
console.log(JSON.parse(fileData));
}
});

Node events.js:174 throw er; // Unhandled 'error' event

I get an error when requesting an API and it crashes on any win server. Can anybody help, please?
This is part of my code:
app.get("/js/2806/api/products/getAllDrugs", (req, res) => {
const connection = getDBConnection()
const queryString = "SELECT * FROM tbl_drug";
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log("Failed to query for drugs: " + err);
// res.sendStatus(500);
res.json({
ErrorDetail: {
code: -1,
msg: err.code
}
});
res.end();
return
}
const drugs = rows.map((row) => {
return {
id: row.id,
storeId: row.drugStoreId,
drugName: row.drugName,
description: row.drugDsc,
drugUsing: row.drugUsing,
drugDoseId: row.drugDoseId,
categoryId: row.categoryId
};
})
res.json({
ErrorDetail: {
code: 0
},
Response: drugs
})
})
});
Error: Connection lost: The server closed the connection. at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:112:13) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:502:10) at Socket.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1125:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at Connection._handleProtocolError (C:\Users\Administrator\AppData\ ainCure\node_modules\mysql\lib\Connection.js:425:8) at Protocol.emit (events.js:189:13) at Protocol._delegateError (C:\Users\Administrator\AppData\Local\Ca node_modules\mysql\lib\protocol\Protocol.js:390:10) at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:116:8) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) I— lines matching original stack trace ...] at process._tickCallback Cinternal/process/next_tick.js:63:19> [nodemon I - wait in is (nodemon] si ing 'node app.js -erver is running on port: 3000 ode events.js:174 throw er; // Unhandled 'error' event is (nodemon] starting 'node app.js' -erver is running on port: 3000
Because of the server is already running on back so we do have to restart.
and if your using both iterm and the terminal so you need to make sure that the you use only one other one you have to close.

How to fix MaxListenersExceededWarning error?

In my Node.js http web server I use ssh2-sftp-client library to load csv files from remote SFTP server. It raise error when user try to load several files and I don't understand how to fix it?
CODE:
router.post('/', (req, res) => {
const fileName = req.body.file_name
const remotePath = '/reports/' + fileName
const localePath = path.join(process.env.HOME || process.env.USERPROFILE, 'Downloads/' + fileName)
sftp.connect(config.sftpServer, 'on').then(() => {
sftp.fastGet(remotePath, localePath, {}).then(() => {
res.header('Content-type', 'text/csv; charset=windows-1251')
res.sendFile(localePath)
sftp.end()
}).catch((err) => {
sftp.end()
console.log(err, 'fastGet method error')
})
}).catch((err) => {
sftp.end()
console.log(err, 'connect method error')
})
})
ERROR:
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Finally I found the problem. Instead of on method you need to use once method.
sftp.connect(config.sftpServer, 'once').then(() => {
// CODE
}

TypeError: Cannot read property 'title' of null

I am getting this JavaScript error:
TypeError: Cannot read property 'title' of null
Here is the code:
Mds-iMac:cmscart imac$ nodemon app
[nodemon] 1.11.0
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app app.js
(node:2274) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client
(node:2274) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
Server started on port 3200
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
Connected to MongoDB
events.js:182
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'title' of null
at /Users/imac/Desktop/cmscart/routes/pages.js:17:24
at model.Query.<anonymous> (/Users/imac/Desktop/cmscart/node_modules/mongoose/lib/model.js:4074:16)
at /Users/imac/Desktop/cmscart/node_modules/kareem/index.js:273:21
at /Users/imac/Desktop/cmscart/node_modules/kareem/index.js:131:16
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...
The page.js code is:
var express = require('express');
var router = express.Router();
// Get Page model
var Page = require('../models/page');
/*
* GET /
*/
router.get('/', function (req, res) {
Page.findOne({slug: 'home'}, function (err, page) {
if (err)
console.log(err);
res.render('index', {
title: page.title,
content: page.content
});
});
});
/*
* GET a page
*/
router.get('/:slug', function (req, res) {
var slug = req.params.slug;
Page.findOne({slug: slug}, function (err, page) {
if (err)
console.log(err);
if (!page) {
res.redirect('/');
} else {
res.render('index', {
title: page.title,
content: page.content
});
}
});
});
// Exports
module.exports = router;
The error is occuring inside the JavaScript functions at title: page.title, above.
Please help me out.
router.get('/edit-page/:slug', (req, res) => {
Page.findOne({slug : req.params.slug}).then((page) => {
if(!page) { //if page not exist in db
return res.status(404).send('Page not found');
}
res.render('admin/edit_page', { //page exist
title: page.title,
slug: page.slug,
content: page.content,
id: page._id
});
}).catch((e) => {//bad request
res.status(400).send(e);
});
});
Use this code it will work the logic is same but i have handled the conditions using promises it definitely worked for me. Hope it helps you :)
It means that when
function (err, page) {
was called, inside of Page.findOne, the page argument did not have a property of title.
(without context of how Page.findOne is being used, hard to say how to fix it)
if (err)
console.log(err);
Is one issue. When you get an error you should return an http error then exit the function eg:
if (err) {
console.log(err);
res.statusCode = 500;
res.end('error');
}
When there is an error the page variable will be null, which explains the exception thrown.

connection error while connecting mongodb to node application

after I started server at port 27017, opened another window and run my server program it is showing the connection error as follow
C:\node-mongodb\node_modules\mongodb\lib\server.js:242
process.nextTick(function() { throw err; })
^
AssertionError: { [MongoError: connect UNKNOWN 127.0.0.1:27017 -
Local(undefined:undefined)]
name: 'MongoError',
message: 'connect UNKNOWN == null
at C:\node-mongodb\simple-server.js:8:12
at C:\node-mongodb\node_modules\mongodb\lib\mongo_client.js:330:20
at C:\node-mongodb\node_modules\mongodb\lib\db.js:231:14
at null.<anonymous> (C:\node-mongodb\node_modules\mongodb\lib\server.js:240:9)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous(C:\nodemongodb\node_modules\mongodb\node_modules\mongo
db-core\lib\topologies\server.js:218:12)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
I tried removing lock file repairing mongodb and other solutions that are given for other similar questions but they are not working.
please tell my why this error is coming and how I can resolve it.
I am running on windows xp(32-bit).
This is the simple-server.js file:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(err,null);
console.log("Connected correctly to server");
var collection = db.collection("dishes");
collection.insertOne({name: "nerd21", description: "test"},
function(err,result){
assert.equal(err,null);
console.log("After Insert:");
console.log(result.ops);
collection.find({}).toArray(function(err,docs){
assert.equal(err,null);
console.log("Found:");
console.log(docs);
db.dropCollection("dishes", function(err, result){
assert.equal(err,null);
db.close();
});
});
});
});
screenshot of command prompt is as follows:enter image description here

Categories

Resources