Basic Node.js examples not working on Windows 7 - windows

I installed node.js from http://nodejs.org/#download, v0.6.6. I am using Windows 7 32-bit.
I've been going through various tuts online, and want to experiment while doing so, but I cannot seem to get node.js working. Node will run my .js file, but any request from the browser times out.
Here is a typical Hello World example that does not work:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
Pointing my browser at 127.0.0.1:1337 or localhost:1337 does not work. The request from the browser times out. I've also tried listen(1337,'0.0.0.0') and listen(1337,'127.0.0.1').
I know the server is running; if I CTRL+C and stop node, the browser immediately comes back with ERR_CONNECTION_RESET.
I also tried running the code in this gist, which will not work: https://gist.github.com/1339846. I end up with the console output "Listening!" and then nothing else.
Furthermore, I have tried different ports, and my firewall is off via
netsh firewall set opmode mode=disable
I tried with firewall totally disabled, and the service stopped. If I check connections using netstat -noa, I can see node has a bunch of connections opened for the browsers, all in state CLOSE_WAIT. So it looks like connections are happening, but node.js just isn't working.
The callback function that is supposed to be initiated by a request never executes - I sprinkled some console.log statements in various areas, and they all execute except any in the callback.
I uninstalled, re-installed, tried a couple previous builds, restarted my machine...nothing.
Any help is appreciated!
UPDATE: I have just about given up. I've tried everything I can think of, and it ended up being easier to run node.js in an instance of Ubuntu in VirtualBox than grasp at straws.

!!!!!! Same problem happened for me....
Here is a solution which I have yet to find anywhere:
Look in Windows Firewall with Advanced Security and see if Evented I/O for V8 JavaScript is blocked or appears two times.
If so unblock it and delete the duplicated entry. If you install/uninstall/install nodeJs, there will be 2 entries.
Also when node first runs the Window Firewall dialog opens asking if you want to allow node to have firewall access. If you press "No" or just close the window without asking, it will create Evented I/O for V8 JavaScript AND IT WILL BE BLOCKED.

I ran into the same problem and after reading through the documentation, I unexpectedly ran into what I believe is the solution. In my instance I was noticing that the incoming requests WERE being delivered to node, but the response was never having its 'end' event triggered. So altering incoming firewall rules in windows did not seem to be related to the problem.
So, http.createServer takes in a single argument - a function which should include a request and response parameter. The request parameter seemed to be where the problem lay. The request parameter is an instance of http.incomingMessage. This class only had like one event type, but it was itself also an implementation of Stream.Readable, which is where I found the 'end' event that wasn't triggered. Really for no other reason that to just test which was the first event not triggered, I just added a listener for another type of event ('readable'), and only added a console.log line to it which made the whole thing work.
So the code looks simply something like this:
var http = require("http");
http.createServer(function (request, response) {
console.log('request');
request.on('readable', function(){
console.log('request readable');
});
request.on("end", function () {
console.log('request end');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
The above code works, whereas the earlier version below without a 'readable' event listener does not ever respond:
var http = require("http");
http.createServer(function (request, response) {
console.log('request');
request.on("end", function () {
console.log('request end');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
I am not sure why this works except for a little clue in the documentation which reads:
In some cases, listening for a 'readable' event will cause some data
to be read into the internal buffer from the underlying system, if it
hadn't already.

I just tried it and it works for me. Make sure you are not blocking node with your firewall.

I am using Windows 7 32-bit.
What edition of Windows 7 are you using? Eg. Home Premium, Professional, Ultimate?
A thread on the npm github project mentions similar symptoms while installing nodejs modules using npm, and comments seem to narrow it down to being caused by Windows 7 Professional. It being 32/64-bit doesn't seem to matter.
I am having both the problem you describe, as well as the npm installation problem, and am running on Windows 7 Professional 64-bit.
Using XPMode (a workaround mentioned in the npm thread) has allowed me to workaround both of these issues. Although, I suppose this is just a more Windows-y version of your use of Ubuntu in VirtualBox.
Other workarounds tried without success:
Make/run a Debug build of v0.6.6
Make/run a Debug build of v0.6.5 (actually crashed in startup)
Set various Compatability Modes on the installed node.exe
Prepackaged Windows installer of v0.6.5

Go to "Control Panel\All Control Panel Items\Windows Firewall\Allowed
Programs"
Click Allow Programs
select nodejs from the list.
This fixed all the problems for me

I was having the same problem with this code (Http Server example from this link: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/)
var http = require("http");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
I tried windows 7 64-bit version, windows XP virtual machine, ubuntu virtual machine ... nothing! It only worked after I commented the "request.on" line. Your example (which doesn't have this line) worked fine for me. I'm using the latest stable build from node.js (v0.10.18 for windows or linux). Hope this helps anyone having trouble with this.

Related

P5.js not loading sound

I am trying to load an mp3 files (according to the examples) but I am getting
Unable to load bg.mp3.
The request status was: 0 ()
The error stack trace includes: loadSound
I have referenced my problem to this Github issue https://github.com/processing/p5.js-sound/issues/141 but I am unable to find a solution.
Also, I am using Brackets editor which starts a local server and opens a new Chrome instance.
let mySound;
function preload() {
soundFormats('mp3', 'ogg');
mySound = loadSound("bg.mp3");
}
function setup(){
createCanvas(displayWidth,displayHeight);
mySound.setVolume(0.1);
mySound.play();
}
Strange, the Sound: Load and Play Sound example seems to work fine.
The error seems to point to on an XHR load error, but it's unclear why.
It's worth trying the full version of loadSound() including the error callback:loadSound(path, [successCallback], [errorCallback], [whileLoading]).
Hopefully the errorCallback details will help solve the problem
e.g.
let mySound;
function onSoundLoadSuccess(e){
console.log("load sound success",e);
}
function onSoundLoadError(e){
console.log("load sound error",e);
}
function onSoundLoadProgress(e){
console.log("load sound progress",e);
}
function preload() {
soundFormats('mp3', 'ogg');
mySound = loadSound("bg.mp3",onSoundLoadSuccess,onSoundLoadError,onSoundLoadProgress);
}
function setup(){
createCanvas(displayWidth,displayHeight);
mySound.setVolume(0.1);
mySound.play();
}
Also try to navigate to the web server Brackets launches and access the file manually.
(e.g. http://localhost:BRACKETS_HTTP_PORT_HERE/bg.mp3). If everything is ok (bg.mp3 is in the same folder as the index.html file), your browser should load and display the default audio playback controls.
It's worth noting there are many other http servers you could try, here a few examples:
if you're on OSX you can use Python's HTTP Server (python -m SimpleHTTPServer in python 2 or python -m http.server)
if you use node.js there' an http-server module (e.g. npm install http-server then http-server in your project folder)
Apache variants (depending on OS, MAMP/WAMP/XAMPP, etc.), though might be overkill
The quick fix for anyone having this issue is to use a Local web server. (mamp/xamp/local etc). Then reference it in the preload/setup
sound = loadSound('http://localhost/audio.mp3', loaded);
The documentation does state -
you will need the p5.sound library and a running local server

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I'm using VueJS and Laravel for my project. This issue started to show lately and it shows even in the old git branches.
This error only shows in the Chrome browser.
I disabled all installed extensions in Chrome - works for me.
I have now clear console without errors.
In case you're an extension developer who googled your way here trying to stop causing this error:
The issue isn't CORB (as another answer here states) as blocked CORs manifest as warnings like -
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://www.example.com/example.html with MIME type text/html. See
https://www.chromestatus.com/feature/5629709824032768 for more
details.
The issue is most likely a mishandled async response to runtime.sendMessage. As MDN says:
To send an asynchronous response, there are two options:
return true from the event listener. This keeps the sendResponse
function valid after the listener returns, so you can call it later.
return a Promise from the event listener, and resolve
when you have the response (or reject it in case of an error).
When you send an async response but fail to use either of these mechanisms, the supplied sendResponse argument to sendMessage goes out of scope and the result is exactly as the error message says: your message port (the message-passing apparatus) is closed before the response was received.
Webextension-polyfill authors have already written about it in June 2018.
So bottom line, if you see your extension causing these errors - inspect closely all your onMessage listeners. Some of them probably need to start returning promises (marking them as async should be enough). [Thanks #vdegenne]
If you go to chrome://extensions/, you can just toggle each extension one at a time and see which one is actually triggering the issue.
Once you toggle the extension off, refresh the page where you are seeing the error and wiggle the mouse around, or click. Mouse actions are the things that are throwing errors.
So I was able to pinpoint which extension was actually causing the issue and disable it.
Post is rather old and not closely related to Chrome extensions development, but let it be here.
I had same problem when responding on message in callback. The solution is to return true in background message listener.
Here is simple example of background.js. It responses to any message from popup.js.
chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
// setTimeout to simulate any callback (even from storage.sync)
setTimeout(function() {
sendResponse({status: true});
}, 1);
// return true; // uncomment this line to fix error
});
Here is popup.js, which sends message on popup. You'll get exceptions until you un-comment "return true" line in background.js file.
document.addEventListener("DOMContentLoaded", () => {
chrome.extension.sendMessage({action: "ping"}, function(resp) {
console.log(JSON.stringify(resp));
});
});
manifest.json, just in case :) Pay attention on alarm permissions section!
{
"name": "TestMessages",
"version": "0.1.0",
"manifest_version": 2,
"browser_action": {
"default_popup": "src/popup.html"
},
"background": {
"scripts": ["src/background.js"],
"persistent": false
},
"permissions": [
"alarms"
]
}
To me i was using a VPN extension called
Free VPN for Chrome - VPN Proxy VeePN It was causing the error after disabling it only ... the error disappeared
This error is generally caused by one of your Chrome extensions.
I recommend installing this One-Click Extension Disabler, I use it with the keyboard shortcut COMMAND (⌘) + SHIFT (⇧) + D — to quickly disable/enable all my extensions.
Once the extensions are disabled this error message should go away.
Peace! ✌️
If error reason is extension use incognito Ctrl+Shift+N. In incognito mode Chrome does not have extensions.
UPD. If you need some extension in incognito mode e.g. ReduxDevTools or any other, in extension settings turn on "Allow in incognito"
Make sure you are using the correct syntax.
We should use the sendMessage() method after listening it.
Here is a simple example of contentScript.js It sendRequest to app.js.
contentScript.js
chrome.extension.sendRequest({
title: 'giveSomeTitle', params: paramsToSend
}, function(result) {
// Do Some action
});
app.js
chrome.extension.onRequest.addListener( function(message, sender,
sendResponse) {
if(message.title === 'giveSomeTitle'){
// Do some action with message.params
sendResponse(true);
}
});
For those coming here to debug this error in Chrome 73, one possibility is because Chrome 73 onwards disallows cross-origin requests in content scripts.
More reading:
https://www.chromestatus.com/feature/5629709824032768
https://www.chromium.org/Home/chromium-security/extension-content-script-fetches
This affects many Chrome extension authors, who now need to scramble to fix the extensions because Chrome thinks "Our data shows that most extensions will not be affected by this change."
(it has nothing to do with your app code)
UPDATE: I fixed the CORs issue but I still see this error. I suspect it is Chrome's fault here.
In my case it was a breakpoint set in my own page source. If I removed or disabled the breakpoint then the error would clear up.
The breakpoint was in a moderately complex chunk of rendering code. Other breakpoints in different parts of the page had no such effect. I was not able to work out a simple test case that always trigger this error.
I suggest you first disable all the extensions then one by one enable them until you find the one that has caused the issue in my case Natural Reader Text to Speech was causing this error so I disabled it. nothing to do with Cross-Origin Read Blocking (CORB) unless the error mention Cross-Origin then further up the tread it is worthwhile trying that approach.
I faced the same error in my react project running.
That error coming from my chrome
IObit Surfing Protection
2.2.7
extensions. That extension off my error was solved.
If you face same like that error, 1st turn off your chrome ad blocker or any other extensions while running.
Late here but in my case it was Kaspersky Cloud Protection Extension. I disabled it. It worked all good.
The cause of this issue is related to one of your chrome extensions, not CORS or CORB. To fix that you can turn off each and every chrome extension you installed.
Norton Safe Web extension for chrome is throwing this error message for me. After I disabled this extension, the error message disappeared.
Just cleaning site cookies worked here.
In my case i had to switch off "Adblock extension" from chrome.

HttpClient->GetStringAsync() throws 0x000006F4 for https Uris

The code below works fine for me if I use an http URI, but fails for equivalent https alternative. It works fine when built and run on another machine or when I include it in another app.
GetStringAsync throws an exception: “Exception thrown at 0x770B5722 (KernelBase.dll) in .exe: 0x000006F4: A null reference pointer was passed to the stub. occurred”.
ThreadPool::RunAsync(ref new WorkItemHandler([this](IAsyncAction^ action)
{
HttpClient^ client = ref new HttpClient();
auto uri = ref new Uri(L"https://....");
auto t = create_task(client->GetStringAsync(uri));
t.then([](String^ response)
{
// response should be valid.
});
}));
Running netsh winsock reset to reset the network stack seems to fix the issue!
For me, network stack reset didn't help at all, even device reboot didn't help, but your own answer have pointed me in the right direction: it wasn't my code who suddendly went mad, it was Windows. So what actually helped in my case is starting app without debugger (that is, from Start menu) - after that app continues to work fine when started from Visual Studio. It have happened a few times now, and I can confirm that it always helps.

Accessing Webapi on Localhost on Dev Machine from Android Emulator

This may well be a duplicate question, but no answer from an existing question has solved my problem.
I have a WebAPI end point running on my dev machine. I've configured it to run on
.UseUrls("http://localhost:57971", "http://10.0.2.2:57971", "http://192.168.44.1:57971", "http://192.168.1.48:57971", "http://*:57971")
where:
192.168.44.1 is Desktop Adapter #2 on the emulator Networks settings tab
10.0.2.2 is the special address for the Android emulator, as set out in Google's doco (possibly not relevant to Xamarin) and
192.168.1.48 is my local IP address for my dev machine.
I have created a firewall rule permitting connections on TCP port 57971.
I researched this pretty heavily and heeded instructions such as those set out here http://briannoyesblog.azurewebsites.net/2016/03/06/calling-localhost-web-apis-from-visual-studio-android-emulator/
I'm kinda out of ideas. The annoying thing is, it fails silently. There is no exception and the output just basically shows the different threads exiting with code 0. And the application keeps running i.e. the debugging session is not returning the IDE to a "code entry" state. This may suggest that something else its at play here.
The code looks pretty innocuous to me:
protected async Task<T> GetAsync<T>(string url)
where T : new()
{
HttpClient httpClient = CreateHttpClient();
T result;
try
{
var response = await httpClient.GetStringAsync(url);
result = await Task.Run(() => JsonConvert.DeserializeObject<T>(response));
}
catch
{
result = new T();
}
return result;
}
I'm using Visual Studio 2015.
I'm using the Visual Studio emulator https://www.visualstudio.com/vs/msft-android-emulator/
Any idea how I can get wheels on the ground on this thing?
Is there a way to Ping my machine from the emulator?
Thanks
I got this working by using 169.254.80.80 i.e. I added it to the list of urls which the API serves and called that ip address from the Xamarin app.
So, in Program.cs became simple:
.UseUrls("http://localhost:57971", "http://169.254.80.80:57971")
I also had to add it to the bindings element ApplicationConfig file in the hidden .vs folder of the ASP.NET API solution. Not sure why it had to be 169.254.80.80, as that was Desktop Adapter #4.
That got it working.

How to Stop the page loading in firefox programmatically?

I am running several tests with WebDriver and Firefox.
I'm running into a problem with the following command:
WebDriver.get(www.google.com);
With this command, WebDriver blocks till the onload event is fired. While this can normally takes seconds, it can take hours on websites which never finish loading.
What I'd like to do is stop loading the page after a certain timeout, somehow simulating Firefox's stop button.
I first tried execute the following JS code every time that I tried loading a page:
var loadTimeout=setTimeout(\"window.stop();\", 10000);
Unfortunately this doesn't work, probably because :
Because of the order in which scripts are loaded, the stop() method cannot stop the document in which it is contained from loading 1
UPDATE 1: I tried to use SquidProxy in order to add connect and request timeouts, but the problem persisted.
One weird thing that I found today is that one web site that never stopped loading on my machine (FF3.6 - 4.0 and Mac Os 10.6.7) loaded normally on other browsers and/or computers.
UPDATE 2: The problem apparently can be solved by telling Firefox not to load images. hopefully, everything will work after that...
I wish WebDriver had a better Chrome driver in order to use it. Firefox is disappointing me every day!
UPDATE 3: Selenium 2.9 added a new feature to handle cases where the driver appears to hang. This can be used with FirefoxProfile as follows:
FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("web");
firefoxProfile.setPreference("webdriver.load.strategy", "fast");
I'll post whether this works after I try it.
UPDATE 4: at the end none of the above methods worked. I end up "killing" the threads that are taking to long to finish. I am planing to try Ghostdriver which is a Remote WebDriver that uses PhantomJS as back-end. PhantomJS is a headless WebKit scriptable, so i expect not to have the problems of a real browser such as firefox. For people that are not obligate to use firefox(crawling purposes) i will update with the results
UPDATE 5: Time for an update. Using for 5 months the ghostdriver 1.1 instead FirefoxDriver i can say that i am really happy with his performance and stability. I got some cases where we have not the appropriate behaviour but looks like in general ghostdriver is stable enough. So if you need, like me, a browser for crawling/web scraping purposes i recomend you use ghostdriver instead firefox and xvfb which will give you several headaches...
I was able to get around this doing a few things.
First, set a timeout for the webdriver. E.g.,
WebDriver wd;
... initialize wd ...
wd.manage().timeouts().pageLoadTimeout(5000, TimeUnit.MILLISECONDS);
Second, when doing your get, wrap it around a TimeoutException. (I added a UnhandledAlertException catch there just for good measure.) E.g.,
for (int i = 0; i < 10; i++) {
try {
wd.get(url);
break;
} catch (org.openqa.selenium.TimeoutException te) {
((JavascriptExecutor)wd).executeScript("window.stop();");
} catch (UnhandledAlertException uae) {
Alert alert = wd.switchTo().alert();
alert.accept();
}
}
This basically tries to load the page, but if it times out, it forces the page to stop loading via javascript, then tries to get the page again. It might not help in your case, but it definitely helped in mine, particularly when doing a webdriver's getCurrentUrl() command, which can also take too long, have an alert, and require the page to stop loading before you get the url.
I've run into the same problem, and there's no general solution it seems. There is, however, a bug about it in their bug tracking system which you could 'star' to vote for it.
http://code.google.com/p/selenium/issues/detail?id=687
One of the comments on that bug has a workaround which may work for you - Basically, it creates a separate thread which waits for the required time, and then tries to simulate pressing escape in the browser, but that requires the browser window to be frontmost, which may be a problem.
http://code.google.com/p/selenium/issues/detail?id=687#c4
My solution is to use this class:
WebDriverBackedSelenium;
//When creating a new browser:
WebDriver driver = _initBrowser(); //Just returns firefox WebDriver
WebDriverBackedSelenium backedSelenuium =
new WebDriverBackedSelenium(driver,"about:blank");
//This code has to be put where a TimeOut is detected
//I use ExecutorService and Future<?> Object
void onTimeOut()
{
backedSelenuium.runScript("window.stop();");
}
It was a really tedious issue to solve. However, I am wondering why people are complicating it. I just did the following and the problem got resolved (perhaps got supported recently):
driver= webdriver.Firefox()
driver.set_page_load_timeout(5)
driver.get('somewebpage')
It worked for me using Firefox driver (and Chrome driver as well).
One weird thing that i found today is that one web site that never stop loading on my machine (FF3.6 - 4.0 and Mac Os 10.6.7), is stop loading NORMALy in Chrome in my machine and also in another Mac Os and Windows machines of some colleague of mine!
I think the problem is closely related to Firefox bugs. See this blog post for details. Maybe upgrade of FireFox to the latest version will solve your problem. Anyway I wish to see Selenium update that simulates the "stop" button...
Basically I set the browser timeout lower than my selenium hub, and then catch the error. And then stop the browser from loading, then continue the test.
webdriver.manage().timeouts().pageLoadTimeout(55000);
function handleError(err){
console.log(err.stack);
};
return webdriver.get(url).then(null,handleError).then(function () {
return webdriver.executeScript("return window.stop()");
});
Well , the following concept worked with me on Chrome , try the same:
1) Navigate to "about:blank"
2) get element "body"
3) on the elemënt , just Send Keys Ësc
Just in case someone else might be stuck with the same forever loading annoyance, you can use simple add-ons such as Killspinners for Firefox to do the job effortlessly.
Edit : This solution doesn't work if javascript is the problem. Then you could go for a Greasemonkey script such as :
// ==UserScript==
// #name auto kill
// #namespace default
// #description auto kill
// #include *
// #version 1
// #grant none
// ==/UserScript==
function sleep1() {
window.stop();
setTimeout(sleep1, 1500);
}
setTimeout(sleep1, 5000);

Resources