gulp.watch error: write after end - node.js

I am getting different results for different gulp.watch instruction
When I execute my watch task and change an .html file, everything works correctly (tasks defined below)
But when I change any other files (.coffee, .less, etc) I get this error:
stream.js:94
throw er; // Unhandled stream error in pipe.
^
Error: write after end
at writeAfterEnd (/Users/oclement/Documents/phoenix/MedifastCerBrokenDown/MedifastWeb/AppSource/node_modules/gulp-filter/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:145:12)
at Transform.Writable.write (/Users/oclement/Documents/phoenix/MedifastCerBrokenDown/MedifastWeb/AppSource/node_modules/gulp-filter/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:193:5)
at Stream.ondata (stream.js:51:26)
at Stream.emit (events.js:95:17)gulp.watch`
Watch Task
gulp.task('watch', function() {
isWatching = true;
run('build', 'index', function() {
g.util.log(g.util.colors.green('Starting to Watch'));
gulp.watch('./app/**/*.html', ['templates']);
gulp.watch('./app/**/*.coffee', ['phnxjs']);
...
});
});
Template Task
gulp.task('templates', function(done) {
g.util.log(g.util.colors.green('---TEMPLATES---'));
sourceStreams.templates()
.pipe(buildWatchPipe()())
.pipe(g.ngHtml2js(options.templates))
.pipe(g.concat(destinations.templates.bundleName))
.pipe(g.if(isProd, transformScriptsProd()))
.pipe(destinations.templates.target())
.pipe(g.if(isWatching, g.livereload()));
done();
});
Phnxjs Task
gulp.task('phnxjs', function(done) {
g.util.log(g.util.colors.green('---PHNXJS---'));
var wrapException = g.filter('!**/tags-input.js');
sourceStreams.phoenixScripts()
.pipe(buildWatchPipe()())
.pipe(filters.coffee)
.pipe(g.coffee(options.coffee))
.on('error', g.util.log)
.pipe(filters.coffee.restore())
.pipe(wrapException)
.pipe(iffeWrapper())
.pipe(wrapException.restore())
.pipe(g.if(!isProd, g.angularFilesort()))
.pipe(g.if(isProd, transformScriptsProd()))
.pipe(g.if(isProd, g.concat(destinations.phoenixScripts.bundleName)))
.pipe(destinations.phoenixScripts.target())
.pipe(g.if(isWatching, g.livereload()));
done();
});

Related

throw er; // Unhandled stream error in pipe: Error: ENOENT: no such file or directory

I've tried multiple solutions coming from: How to download a file with Node.js (without using third-party libraries)?
I have the following path related error:
internal/streams/legacy.js:57
throw er; // Unhandled stream error in pipe.
^
Error: ENOENT: no such file or directory, open 'bot_side/img/image.jpg'
My app structure looks like this:
My code is the following:
download(url, path, () => {
return imageClassification(path)
})
const download = (url, path, callback) => {
request.head(url, (err, res, body) => {
request(url)
.pipe(fs.createWriteStream(path))
.on('close', callback)
})
}
Thanks.

NodeJS -> Error: write after end (only after first request)

In my express app i have the route below:
router.get('/generatedData', function (req, res) {
res.setHeader('Connection' , 'Transfer-Encoding');
res.setHeader('Content-Type' , 'text/html; charset=utf-8');
res.setHeader('Transfer-Encoding' , 'chunked');
var Client = someModule.client;
var client = Client();
client.on('start', function() {
console.log('start');
});
client.on('data', function(str) {
console.log('data');
res.write(str);
});
client.on('end', function(msg) {
client.stop();
res.end();
});
client.on('err', function(err) {
client.stop();
res.end(err);
});
client.on('end', function() {
console.log('end');
});
client.start();
});
On first call everything works fine (console)
We've got ourselves a convoy on port 3000
start
data
data
data
data
data
...
data
end
GET /generatedData 200 208.426 ms - -
I get all the data and res.end() is being called and successfully closes the request.
The problem starts after first request. I make the exact same request (new one of course) and i get the following error (console):
start
data
data
data
events.js:160
throw er; // Unhandled 'error' event
^
Error: write after end
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
at Client.<anonymous> (/Users/xxxx/projects/xxxx/routes/index.js:33:17)
at emitOne (events.js:96:13)
at Client.emit (events.js:188:7)
at FSWatcher.<anonymous> (/Users/xxxx/projects/xxxx/lib/someModule.js:116:32)
at emitTwo (events.js:106:13)
at FSWatcher.emit (events.js:191:7)
at FSEvent.FSWatcher._handle.onchange (fs.js:1412:12)
[nodemon] app crashed - waiting for file changes before starting...
This happens without res.end() being called.
I manage to get some data before the crash.
How can i get this error without res.end() being called at all?
Do i somehow save the previous res instance?
Thanks,
Asaf
Have the same problem. My module was extened by EventEmitter and each time i catch event in router - it stays there, end on second call there are two eventlisteners not one. Setting "once" instead of "on" - worked for me.
client.once('start', function() {
console.log('start');
});
instead of
client.on('start', function() {
console.log('start');
});

How to test a function that throws an error asynchronously, using tape?

I am attempting to test this module (receiver.js) for an error thrown:
var request = require('request')
module.exports = function(url){
request({
url: url,
method: 'POST'
}, function(error) {
if(error){
throw error
}
})
}
using this test (test.js):
var test = require('tape')
test('Receiver test', function(t){
var receiver = require('./receiver')
t.throws(function(){
receiver('http://localhost:9999') // dummy url
}, Error, 'Should throw error with invalid URL')
t.end()
})
but tape runs the assertion before the error is thrown, resulting in the following error message:
TAP version 13
# Receiver test
not ok 1 Should throw error with invalid URL
---
operator: throws
expected: |-
[Function: Error]
actual: |-
undefined
at: Test.<anonymous> (/path/to/tape-async-error-test/test.js:5:4)
...
/path/to/receiver.js:9
throw error
^
Error: connect ECONNREFUSED 127.0.0.1:9999
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)
Is there a way around this?
Generally, using tape, you have to ensure you call assert.end() after the async call has completed. Using promises (would require request-promise and returning the promise):
test('Receiver test', function(t){
// Tells tape to expec a single assertion
t.plan(1);
receiver('http://localhost:9999')
.then(() => {
t.fail('request should not succeed')
})
.catch(err => {
t.ok(err, 'Got expected error');
})
.finally({
t.end();
});
});
Using async/await:
test('Receiver test', async function(t) {
try {
await receiver('http://localhost:9999');
assert.fail('Should not get here');
} catch (err) {
assert.ok(err, 'Got expected error');
}
t.end();
});
The above example is mostly correct but here's a complete working example that compares async to synchronous side by side and also shows how to check for the error message in a manner similar to the tape examples given on tape's README.md.
test('ensure async function can be tested to throw', async function(t) {
// t.throw works synchronously
function normalThrower() {
throw(new Error('an artificial synchronous error'));
};
t.throws(function () { normalThrower() }, /artificial/, 'should be able to test that a normal function throws an artificial error');
// you have to do this for async functions, you can't just insert async into t.throws
async function asyncThrower() {
throw(new Error('an artificial asynchronous error'));
};
try {
await asyncThrower();
t.fail('async thrower did not throw');
} catch (e) {
t.match(e.message,/asynchronous/, 'asynchronous error was thrown');
};
});

ECONNREFUSED in Node http module

When a remote site is off-line I am getting this error in my consuming client (Node.js v0.12.0 with the http module):
Uncaught exception: connect ECONNREFUSED
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
The code I'm currently using looks like this:
var req = http.request(options, function (res) {
res.on('socket', function (socket) {
socket.setKeepAlive(true, 0);
socket.setNoDelay(true);
});
res.on('end', function () {
log.debug('Success');
}).on('error', function () {
log.error('Response parsing failed');
});
}).on('error', function () {
log.error('HTTP request failed');
});
req.write(packet);
req.end();
The "error" event is never fired when the ECONNREFUSED occurs, I've tried using the "clientError" event but this is not fired either.
How can I capture this error?
Extracted from: https://stackoverflow.com/a/4328705/4478897
NOTE: This post is a bit old
The next example is with the http.createClient but i think it could be the same
Unfortunately, at the moment there's no way to catch these exceptions directly, since all the stuff happens asynchronously in the background.
All you can do is to catch the uncaughtException's on your own:
process.on('uncaughtException', function (err) {
console.log(err);
});
Maybe that helps you!
More this: https://stackoverflow.com/a/19793797/4478897
UPDATE:
did you tried to change log.error() to console.error() ???

Launching Two Node Child Processes From Single Gulp File Results In Error: listen EADDRINUSE

I'd like to manage two apps with one gulpfile. I can launch them both with the following code. However, when I modify one of the files, and gulp.watch restarts the server, I get Error: listen EADDRINUSE. Something must be wrong in my gulp server task, but what is it?
// Dependencies
var gulp = require('gulp'),
spawn = require('child_process').spawn,
node;
// Server Task
gulp.task('server', function() {
if (api) node.kill();
if (dashboard) node.kill();
var api = spawn('node', ['./api/server.js'], {
stdio: 'inherit'
});
var dashboard = spawn('node', ['./dashboard/server.js'], {
stdio: 'inherit'
});
api.on('close', function(code) {
if (code === 8) console.log('API – Error detected, waiting for changes...');
});
dashboard.on('close', function(code) {
if (code === 8) console.log('Dashboard – Error detected, waiting for changes...');
});
});
// Watch Statement
gulp.task('default', ['server'], function() {
// Watch files for changes
gulp.watch(alljsLocations, ['server'], function() {});
});

Resources