node does not output using console log - javascript

I fairly new to nodejs and I put the following code in some module,
module.exports = function (app) {
app.get('/aa', function(req, res) {
console.log("test");
debugger;
res.send('file updated');
...
the application is working and I see in the browser "file updated"
but I've two problems:
why don't I see "test" in the console?
I set up a debugger (using WebStorm 10) and it does not stop, what am I missing here?
I try also to run the debugger in Webstorm and click on debug and I see in the terminal Debugger listening on port 55236 but when I change the port in the browser nothing happen, any idea?

Node runs server side, so any console.log statements will appear in the the console you ran your script from. You won't see any debug statements in the browser except those from client js code. The reason you see file updated is because you sent that string as a response to your browser, and its simply spitting back the response it got.
Same thing with the debugger. If you are using your browser's debugger, it will only affect client js code, NOT your server code. Not too familiar with WebStorm, but they have instructions for debugging Node.js specific code here

Related

Visual Studio Code, Debugging Node - How can I hit this 'Unverified Breakpoint'?

I'm just starting both with node and VSCode (and to some extent, javascript) so this may be a schoolboy error.
There's just one javascript file, writefile.js :
var fs = require('fs');
process.stdin.on('data', function (text) {
fs.writeFileSync("test.txt", text, 'utf8');
console.log("The file was saved.");
process.exit();
});
console.log('what do you want to write?');
Which works fine with no debugger attached.
Now I'm trying to debug - to keep the scenario simple, I'm just manually launching node in the console with
node --debug-brk writefile.js
If I put a breakpoint on the fs.writeFileSync line, when I attach the debugger in Visual Studio Code, I get a message that it's an 'Unverified Breakpoint':
The other breakpoints are hit fine. I'm expecting all depicted breakpoints be expected to be hit before the writeFileSync one, which should only be hit after the user input at the console.
I tried using the -nolazy option when launching node - but the breakpoint is still showing as unverified, and I also get a long pause while 'Evented IO for v8 javascript' ramps up in memory usage...
What am I doing wrong?
Problem was solved by upgrading node to 4.4.3 - I was on a v0.11 version from 2014.
Would still be interested in why this doesn't work in older versions.

Why am I getting "Your Application is crashing Error" on Meteor.js tutorial?

I just started learning Meteor.js and am following the To-Do App tutorial, which you can view below.
https://www.meteor.com/tutorials/blaze/forms-and-events (this is also the step the error occurred on)
So I was following the directions on the above step and I believe i might of had a type on the Javascript code to listen to the submit event.
I added the submit code (with the type) and went to my web app locally and added some text in the input and pressed enter..then I got this error.
/Users/kassdhs/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:245
throw(ex);
^
ReferenceError: Template is not defined
at simple-todos.js:11:1
at /Users/kassdhs/simple-todos/.meteor/local/build/programs/server/app/simple-todos.js:32:4
at /Users/kassdhs/simple-todos/.meteor/local/build/programs/server/boot.js:242:10
at Array.forEach (native)
at Function._.each._.forEach (/Users/kassdhs/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
at /Users/kassdhs/simple-todos/.meteor/local/build/programs/server/boot.js:137:5
Exited with code: 8
Your application is crashing. Waiting for file change.
TERMINAL ERROR
=> Exited with code: 8
=> Your application is crashing. Waiting for file change.
This happened before when I tried doing the tutorial so I had to reinstall Meteor and re-run the local server to start working on it. Do I have to do this every time I make a type and an error happens?
I hope not because I really like Meteor and feel like I can really learn it fast and strong.
If someone can help me fix this problem that would be amazing (also so I can continue the tutorial!)
Thank you
On the previous step in the tutorial your code simple-todos.js looked like this (extra comments added):
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return Tasks.find({});
}
});
// Add Template.body.event handlers here
} // Closing brace for the Meteor.isClient block
Ensure when you add the submit handler it is within the Meteor.isClient block so that it is only executed on the server.
Template is not defined on the server, causing the ReferenceError.
When you get server side errors, the server will recover when you fix the code. However you may have to manually refresh your web browser before hot code push starts again.

SSE not working as expected on Heroku

It is the first time for me working with Server Sent Events and probably I'm doing something wrong... I just followed a few guides and doing code experiments and locally everything seems to work fine.
Unfortunately when I upload the app on Heroku it doesn't work as expected.
The Javascript looks like this:
// SSE Start
// Check if SSE is supported
if (!!window.EventSource) {
var source = new EventSource('/live/redis');
} else {
console.log('SSE not supported');
}
source.addEventListener('open', function (e) {
console.log('Connection Open');
}, false);
I'm using NodeJS and Redis to get real time messages from the API, but it doesn't matter...
When the SSE connection is open I just print a log on the browser.
I do nothing else at moment and if I open my app locally it just work fine and I receive the console.log message.
If I push the project on Heroku I don't receive any open connection message.
I can not understand why, probably something is missing or probably do I need to configure Heroku to support SSE?
If I open the project with the command heroku local it works fine as well...
EDIT:
From the Heroku logs I receive this:
app/web.1: GET /live/redis 500 86.403 ms - -
I can not understand why, locally it is working fine, on Heroku it isn't.
The error is on my Node.js controller for the route /live/redis that start with this line:
// let request last as long as possible
req.socket.setTimeout(Infinite);
Changing it with the line below solved my problem:
// let request last as long as possible
req.socket.setTimeout(0x7FFFFFFF);
Now I don't know if it is the correct way, but for now it is working.

console.log() does not appear in my terminal (nwjs)

In my nwjs app, I load a _launch.js file from an HTML file:
<html>
<body>
<script type="text/javascript" src="_launch.js"></script>
</body>
</html>
And in my _launch.js file, I fire up the the Node processes I need for an express server and socketIO.
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
gui = require('nw.gui'),
__curDir = process.cwd(),
//keep the logic for the IO connections separate
ioServer = require(__curDir + '/server.js');
//configure Express to default web requests to /workspace/ folder
app.use(express.static(__curDir + '/workspace'));
ioServer.init(io, console);
server.listen(3000, function () {
console.log('HTTP server listening on *:3000');
window.location = 'http://localhost:3000/MyApp/';
});
The app launches just fine, and my express/socketIO connections are all perfectly working.
But while the console.log() in the server.listen() callback appears in my terminal, any messages I try to log from the server.js file (required earlier) never show up anywhere.
Any ideas why?
Per the nwjs wiki, any files loaded via require() should be running in the Node context (and mine otherwise appears to be) -- but for whatever reason, I cannot use console.log() to view logged information.
You have to run DevTools for Background Page by right clicking on your app and choosing the Inspect background page option from the context menu.
click for full size image
Here is a related bug report: 0.13-beta3 console.log doesn't work in node context
Just pass --enable-logging=stderr in chromium-args in your package.json:
{
...
"chromium-args": "--enable-logging=stderr",
...
}
Or use the Inspect background page DevTools as #Jakub Bejnarowicz has pointed out.
Please look at the list of changes related to node in the nw.js wiki.
Since node-webkit supports GUI applications instead of console applications, the output of console.log() (and other similar methods such as console.warn() and console.error()) is redirected to WebKit's console. You may see it in your “Developer Tools” window (on its “Console” tab).

Random 404 from localhost

I'm running a local server in python
python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port"
EDIT: This is the readable version of the command string passed to python -c, so in pseudocode the code block above could be resumed like this: python -c $'command' "$port" where
the command part is:
import SimpleHTTPServer
map = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map
map[""] = "text/plain"
for key, value in map.items():
map[key] = value + ";charset=UTF-8"
SimpleHTTPServer.test()
and I get (seemingly) random 404 errors that prevents my js to execute correctly.
More specifically I am serving a static html page and its linked javascript files.
Chrome tells me net::ERR_ADDRESS_UNREACHABLE and sometimes net::ERR_CONNECTION_REFUSED on this script tag on the index.html page.
<script type="text/javascript" src="http://localhost:8000/lib/fonts.js"></script>
I have 3 weird behavior I don't understand:
if I inspect the terminal log where the python server is running I don't have any 404 error. In fact it says that the file was correctly served (200).
if I go to chrome's Network panel it tells me: Failed to load response data but if I 'open link on a new tab' I can actually see the file!
If I load the file http://localhost:8000/lib/fonts.js on another tab and I refresh many times I never get errors.
sometimes I don't get any 404 errors but my js does not work at all (no js errors)
So who is causing the problem? Chrome, Python or some async behavior in my js?
I suspect that the js files are not loaded in order so other js scripts could not find and use them..
EDIT2:
If I switch server, for example using the built-in php server:
php -S localhost:8000
I won't get the errors
Ok this seems was caused by two different issues:
I've got rid of any async attributes on the <script> nodes. Especially it seems that loading jquery from google with the async attributes was causing most of the problems. Most probably the order of the scripts was not preserved but I've never got any error about jquery being undefined, I was getting an error on the missing script /lib/fonts.js weird..
Even tough removing async made things more reliable, more or less once every 10 page refresh I still got errors of the type net::ERR_ADDRESS_UNREACHABLE or net::ERR_CONNECTION_REFUSED on different external resources, sometimes on a js file, sometimes on a css file. Changing the python server with the php built-in server seems removed the remaining random errors.
So php -S localhost:8000 is more reliable (in my case) than the python counterpart.
NOTE: Even tough I've solved the problem I still don't know exactly what was causing the errors so if someone else has a better answer than this he's very welcome to post. I will leave the answer unaccepted for a while.

Categories

Resources