All errors that i encounter use an absolute file path and i feel that it bogs down the console:
Error: Example Error
at fail (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:276:11)
at assertEquals (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:272:7)
at assertPointEquals (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:262:5)
at assertCreatesHWall (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:258:5)
at testMazeStartingPointCreatesEdgeWall (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:243:5)
at run (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:290:7)
at runTestsFromList (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:285:7)
at runTests (file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:223:5)
at file:///C:/Users/Kris/Projects/Programming/Javascript/maze_generation/src/maze.js:373:13
I feel that it would be much easier to see the relevent information if the irrelevent information were excluded. Maybe something like this for example:
Error: Example Error
at fail (file:./maze.js:276:11)
at assertEquals (file:./maze.js:272:7)
at assertPointEquals (file:./maze.js:262:5)
at assertCreatesHWall (file:./maze.js:258:5)
at testMazeStartingPointCreatesEdgeWall (file:./maze.js:243:5)
at run (file:./maze.js:290:7)
at runTestsFromList (file:./maze.js:285:7)
at runTests (file:./maze.js:223:5)
at file:./maze.js:373:13
Is there any way to change that, or is it all closed off?
There may be a configuration in the console that you are using.
What I would do is run a local server. It is fairly trivial to set up a basic one. Look at NodeJS the home page has an example of how to do this with a few lines of code.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Related
I want to build a MQTT Broker in Typescript with angular. I have tried some examples, but always get the error:
Uncaught TypeError: http.createServer is not a function
Here the simple example i am trying to run at the moment:
var http = require('http');
var port2 = 9000;
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello there, world\n');
}).listen(port2);
console.log("Listening on port " + port2);
Has anyone an idea where i get this error from, or an other example broker I could try?
Thank you for your help!
Your code is probably being run in the browser while using Node.js APIs.
A Node error would look like this:
While a browser error looks more similar to what you refer to in the question.
The snippet I've run for both of these tests is as follows:
var http = {};
var port2 = 9000;
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello there, world\n');
}).listen(port2);
console.log("Listening on port " + port2);
Your provided snippet works OK when run on the latest Nodejs docker image with node.
So I ran into an error reading
TypeError: First argument must be a string or Buffer when running a node.js script, and after a lot of stackoverflow and tutorial googling I couldn't find the solution, so I created sample code literally copy-pasted from the W3Schools node.js tutorial, which still returns the TypeError. The code in question is:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
//Open a file on the server and return it's content:
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
demofile1.html:
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
the console still returns the error
TypeError: First argument must be a string or Buffer
at write_ (_http_outgoing.js:642:11)
at ServerResponse.write (_http_outgoing.js:617:10)
at ReadFileContext.callback (*file path*)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)
I'm assuming that something has to be wrong with my environment, but I've installed node.js and run npm install fs manually, all to no avail. I can run other node.js servers fine, but the error comes when I try to read an html file using fs.
Thanks
I don't recommend W3Schools as a respectable tutorial source, and this is a great example why not: they don't teach good habits like error handling. Because you copied and pasted the example as they had it, your error is rather cryptic. However with good error handling, your error would be caught earlier and give you a much better indication of what went wrong.
With that in mind, try this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
//Open a file on the server and return it's content:
fs.readFile('demofile1.html', function(err, data) {
if (err) throw err; // crash with actual error instead of assuming success
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
It looks that demofile1.html is not found on the same path as where you are starting you server.
I would recommend to:
Try placing the server.js (or whatever you named your js file) in the same path as your demofile1.html and try again
If you need them on subfolders, try navigating with absolute paths, or use some npm extension like rootpath
In the fs callback, try logging data, it is also a good practice to use existsSync() to be sure that your app doesn't crash
nodejs is built upon javascript, but some methods like alert(), writeln(),... etc are not working in nodejs.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(''+alert('server running')+''); // alert() not working here.
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
How can I use these methods in nodejs programs.
These are the browser functions that your trying to call out. You do not have the access to these global objects like window, document, as these are only browser specific.
The rewritten example would be:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
console.log('This will be written in your console');
response.end('server running'); // The response output
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
Those are browser specific methods, of course they don't work in node.
Try console.log( whatYouNeedToLog ) instead.
You can't. They don't make any sense in the context of NodeJS.
If you want to run those functions in the browser, then send the browser an HTML document with embedded JS and not a plain text document.
I am new to Node.js, so I figured I would check it out and do a hello world. I have been having the same issue on all three of my machines, a Win 8, Win 7 and a Mac. Thought at first it was a firewall issue, but I checked and it was off on both Mac and Windows 8 machines (didn't bother checking the win7). When I run Node from the terminal the browser waits for localhost, then eventually times out. I have been at this for two days, can't seem to find any solution via Google. What am I missing.?
Here is my code:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
You don't need to wait for the HTTP request to end (besides that request.on('end', ..) isn't valid and never fires, and that's why you time out). Just send the response:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello HTTP!');
}).listen(8080);
Although if you want an easier way to create a HTTP server, the simplest way would be to use frameworks such as Express. Then your code would look like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.set('Content-Type', 'text/plain');
res.send(200, 'Hello HTTP!');
});
app.listen(8080);
You can also use the connect middleware. Just install it first using npm like so:
npm install -g connect
After this you can make a very simple app like this:
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
res.end('hello world\n');
})
.listen(3000);
You can get more information regarding connect here. I tell you to use this, because you get a very simple server, that is easily extensible. However, if you want to make pull blown web sites, then I would sugges using expressjs.
I've recently ran into a very interesting problem while writing a web app with node.js.
Essentially, all I am doing is serving the index.html page to the client.
Here is the code:
var http = require('http');
var url = require('url');
var fs = require('fs');
var util = require('util');
var server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
if(path == '/'){
console.log("LOADING INDEX...");
openIndex(req, res);
console.log("LOADING COMPLETE.")
} else {
res.write("Something went wrong...");
res.end();
}
}
);
var openIndex = function(req, res){
fs.readFile('./index.html', function(error, content){
if(error){
res.writeHead(500);
res.end();
}
else{
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(content, 'utf-8');
}
});
}
I've put some debugging statements just before and after the index.html page loads: "LOADING INDEX..." and "LOADING COMPLETE".
Now, I have shared the link to my server with my Facebook friends so they can see my app. Most of the time, everything works as it should, but once in a while I get this error:
LOADING INDEX...
This type of response MUST NOT have a body. Ignoring data passed to end().
and just now I've also gotten:
LOADING INDEX...
This type of response MUST NOT have a body. Ignoring write() calls.
The process never raches the "LOADING COMPLETE" statement.
I've tried to reproduce this countless times (accessing my app on different machines, browsers, devices, OS-versions) but every time it works as it should.
I've looked around for other people having this problem, and it seems that somehow, a body is getting into a GET response? I'm not entirely sure what this means or how to fix my code to prevent that from happening. Also, I'm not sure what the clients that produce this error see? Do they get to see my app? (i.e. are these just warnings and as far as they are concerned everything is fine?)
Any help with this will be greatly appreciated.
Xaan
If you're just using a static index.html, why not use express.static to serve it automatically?
app.use("/index.html", express.static(__dirname + '/index.html'));
This would cause expressjs to automatically handle HEAD requests, which should solve your problem.