javascript methods not working in nodejs - javascript

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.

Related

How do I use Node functions and variables from HTML while using a server?

I'm trying to build a few programs that execute Node.js functions from HTML (e.g you press a button and some code using Node.js runs).
Here is the code I'm using to display the HTML
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
(Too long for a comment.)
First you must decide whether pressing a button shall
lead to a complete new HTML page that contains the results of the Node.js code execution or
update only parts of your existing HTML page.
In the first case, sending back static HTML pages (as your code does) will not be sufficient, you would need a template engine.
In the second case, you need client-side Javascript code to fetch JSON data (say) from your server and update the DOM of your HTML page.

Typescript MQTT Broker

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.

How do i make errors use relative paths?

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/');

Getting started with node, waiting for localhost

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.

noob: node.js writeHead stopping my code

Ok, I'm new to Node.js so excuse the noob question. Heres my simple code:
var http = require('http');
var fs = require('fs');
// simple node.js server
server = http.createServer(function (request, response){
var get_text = function (errors, contents){
response.write(contents);
response.end('hello world');
}
// get_text is the callback
fs.readFile('log.txt', get_text);
response.write('End of the callback');
response.writeHead(200);
});
server.listen(8000);
console.log('Server running at port 8000');
As it stands, when I run the script in my terminal it will start the server properly but when I go to my localhost:8000 in my browser (chrome) it comes up as "webpage not available".
If I comment out the writeHead command it works fine.
Why?
This is because you're attempting to .writeHead() after .write():
response.write('End of the callback');
response.writeHead(200);
.writeHead() has to be first:
response.writeHead(200);
response.write('End of the callback\n');

Categories

Resources