Node.js error: write after end - javascript

I have a basic web server with node.js and a root-directory where several .html files are stored. So what I'am doing is
var path = request.url;
getHtmlFile = function(req,res){
fs.readFile('html'+path,funtion(err,data){
if(err){
console.log("no file");
}
else {
res.write(data);
res.end();
console.log("file found");
}
});
}
This code gives me following error :
events.js:141
throw er; // Unhandled 'error' event
^
Error: write after end
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:428:15)
at mypath\server.js:43:18
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)
I'am not very familiar with node.js, so it would be nice, if someone can explain me, what I am missing.

Related

File writing permissions blocked by the EPERM - Deleting then writing a new file. Node.js

I have a file system function which deletes a file then creates a new one with all new data, I am looking for a possible fix for an error that occurs randomly, and not every time, but around every other time. Here is my current code:
try {
if(fs.existsSync(file)) {
fs.unlink(file, function (err) {});
}
} catch (error){
console.log('There was no file to be deleted');
}
fs.open(file, 'w', function (err, file) {
if (err) throw err;
});
var logger = fs.createWriteStream(file, {
flags: 'a' // 'a' means appending (old data will be preserved)
});
which throws the error occasionally:
C:\Users\codel\OneDrive\Documents\BattlEye\index.js:265
if (err) throw err;
^
Error: EPERM: operation not permitted, open 'C:\Users\codel\OneDrive\Documents\BattlEye\files\610636905440215071.txt'
Emitted 'error' event on WriteStream instance at:
at internal/fs/streams.js:375:14
at FSReqCallback.oncomplete (fs.js:171:23) {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\OneDrive\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
First thing that is noticeable is that this is a cloud drive(OneDrive). With my lack of knowledge about permissions, I decided to test out if the problem was in the OneDrive by transferrring the file to my harddrive. The results were not surprising. It didn't change a thing.
C:\Users\codel\Documents\BattlEye\index.js:265
if (err) throw err;
^
[Error: EPERM: operation not permitted, open 'C:\Users\codel\Documents\BattlEye\files\610636905440215071.txt'] {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
But the Emmitted 'error' event on WriteStream disappeared from the error log.
Any ideas on why this error is happening and how to fix it?
It looks like you're using asychronous fs calls. Async calls do not work like that.
You can do a search for NodeJS asynchronous programming.

How to prevent "Error: connect ECONNREFUSED"

I'm currenlty working on a TS3 query bot written in node.js.
I added an auto reconnect to it but I have the issue now that the bot crashes if the server is offline with the following error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
The line which starts the connection is the following:
var cl = new ts3.TeamSpeakClient(config.serverIP);
used with the node-ts api -> https://github.com/nikeee/node-ts
I already added the following events:
cl.on('error', function(err){
console.log("bla: " + err)
});
cl.on('uncaughtException', function (err) {
console.log(err);
});
uncaughtException doesn't get triggered and error doesn't prevent the crash.
How can I prevent it from crashing?
Edit: It's async btw.
You need to catch the UncaughtException on the process rather than in ts3 object.
process.on('uncaughtException', function (err) {
console.log(err);
})
More on handling exceptions can be found over here.
UPDATE:
cl has its own fail promise as well. To be implemented like this:
cl.fail(function(err) {
console.log("An error occurred." + util.inspect(err))
});

Why am i getting this error running 'net' module node.js

I am using .net modular and opening tcp port on 6112.
var net = require('net');
var server = net.createServer(function (socket) { //'connection' listener
});
server.listen(6112, function () { //'listening' listener
console.log('server started');
});
On the same machine i start a java socket in main.
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("Connecting...");
Socket socket = new Socket("localhost", 6112);
System.out.println("Connected");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get this exception,
C:\Users\Mustafa\WebstormProjects\Node.Js>node hello.js
server started
events.js:72
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:884:11)
at TCP.onread (net.js:539:19)
Is this like a bug or something, cause if once i get through this bug, I will be good thanks.
I haven't used the debugger cause as Ryan said it him self a year ago that it is still shitt.
You need to listen for errors on the socket. Node has the default behavior that when something does .emit('error'), if there are no error handlers attached, it will throw the error instead, thus crashing the application.
var server = net.createServer(function (socket) {
socket.on('error', function(err){
// Handle the connection error.
});
});
You are creating a socket and connecting from it, but not closing it. So when the program finishes, to node.js it looks like connection is reset (closed abruptly). Call socket.close(); before program finishes.
You can structure your code in this way :
try {
tryStatements //your code that is causing exceptions
}
catch(exception){
catchStatements //handle caught exceptions
}
finally {
finallyStatements //execute it anyways
}
Or if you like to catch uncaught exceptions from runtime, use this (main process won't exit on exceptions)
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
console.log(err.stack);
});
The problem is in java code which is causing node.js to exit on exception. So be sure to add socket.close();. Above is just error handling on node.js part.

Node.js http.createServer how to get error

I am new to node.js and am trying to experiment with basic stuff.
My code is this
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
Here's the question - how can I see the exceptions thrown (or events thrown) when calling createServer ? I tried try/catch but it doesn't seem to work . In module's API I couldn't find any reference to it . I am asking because I accidentally started a server on a taken port(8888) and the error I got (in command-line) was Error : EDDRINUSE , this is useful enough but it would be nice to be able to understand how errors are caught in node .
You can do this by handling the error event on the server you are creating. First, get the result of .createServer().
var server = http.createServer(function(request, response) {
Then, you can easily handle errors:
server.on('error', function (e) {
// Handle your error here
console.log(e);
});
Print stacktrace of uncaught exceptions using following code.
process.on('uncaughtException', function( err ) {
console.error(err.stack);
});
The error is emitted in the listen() method. The API documentation includes an example just for your situtation.
You can use
process.on('uncaughtException', function(e){
console.log(e);
});
To handle uncaught exceptions. Any unhandled exception from the web server could be caught like this.

Catch exception in node.js

I have a simple program, which needs to make sure I can connect to a Redis server. I use node-redis to connect and need to wait until Redis is started. I use this piece of code:
function initializeRedis(callback) {
(function createClient(){
var runner;
try {
client = redis.createClient();
} catch (e) {
setTimeout(createClient, 1000);
}
callback();
})();
};
initializeRedis(function() {
// Work here
});
This is because without the try/catch, I got an exception from node.js:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused
at Socket.<anonymous> (/var/www/php-jobs/node_modules/redis/index.js:88:28)
at Socket.emit (events.js:64:17)
at Array.<anonymous> (net.js:830:27)
at EventEmitter._tickCallback (node.js:126:26)
When I start redis-server (Ubuntu machine) and start this script, everything works fine. If I stop redis-server and start the script, it doesn't catch the exception and still throws this same exception. How is that possible? I have a try/catch statement!
After client = redis.createClient();, set a handler for the error event:
client.on('error', function(err) {
// handle async errors here
});
Have a look at the stack trace - your code isn't in it, so there's no place where a try/catch could catch the error.

Categories

Resources