// Server.js
var http = require('http');
var path = require('path');
var fs = require('fs');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
// index.html
<html>
<head>
<title>Rockin' Page</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<body>
<p>This is a page. For realz, yo.</p>
</body>
<script type="text/javascript">
$(document).ready(function() {
alert('happenin');
});
</script>
</html>
I am able to run my static page, but i have couple of questions down the line.
What do i do next? i mean what to develop and what to learn? i am confused.. what is the difference i am doing with my current webserver.
Is node.js just an replacement of my Apache Webserver.
Can anyone clearly explain me the main purpose of nodejs
node.js is a platform (language, library, and interpreter), and Turing-complete, i.e. you can do anything with it. Most likely, you'll want a web application which is interactive in some way. Have a look at examples like a chat room. There are also lots of other resources on how to get started.
In the end, it's up to you what you want your site to be. A chatroom? A forum? A search engine? A multiplayer game? If you just want to transfer static files (i.e. have no need for server state or communication between clients), there's no need to use node.js.
Questions
What do i do next? i mean what to develop and what to learn? i am confused.. what is the difference i am doing with my current webserver.
Is node.js just an replacement of my Apache Webserver.
Can anyone clearly explain me the main purpose of nodejs
Answers
Start with some simple examples and/or tutorials. I've forked Mastering Node on github, which is a quick read but is also still a work in progress. I've used expressjs for quickly creating static sites (like my online resume). I also use node.js and nodeunit for testing JavaScript or performing scripting tasks that could otherwise be done in bash, php, batch, perl, etc.
node.js gives an IO wrapper to Google's V8 JavaScript engine. This means that JavaScript is not bound to a web browser and can interact with any type of IO. That means files, sockets, processes (phihag's Turing-complete answer). It can do pretty much anything.
The main purpose of nodejs is that IO code is evented and (mostly) non-blocking. For example, in ASP.NET, when a web server receives a request that request's thread is blocked until all processing is complete (unless processed by an asynchronous handler, which is the exception not the rule). In node.js (express, railwayjs, etc.), the request processing is handled by events and callbacks. Code is executed asynchronously and callbacks are executed when complete. This is similar to the asynchronous pages of ASP.NET, the main difference being that node.js and web frameworks on top of it don't create millions of threads. I believe the threading issue is discussed in Ryan's video.
here is an excellent video from nodejs creator ryan ... http://www.youtube.com/watch?v=jo_B4LTHi3I
it explains what it is with code examples it is really good.
here are some more resources that you can take a look at
http://blog.jayway.com/2011/05/15/a-not-very-short-introduction-to-node-js/
http://www.nodetuts.com/
http://www.howtonode.org/
Related
Playing around with this javascript library
https://www.w3.org/TR/webmidi/#introduction I got some basic functionality working and I was happily able to send midi notes to my syntheseizer and hear it working!..
However, when I wanted to try out the exact same javascript code, but hosted remotely, I got this error:
Uncaught TypeError: window.navigator.requestMIDIAccess is not a function
My code can be boiled down to following:
<html>
<body>
<h1 id="test-result">MIDI test</h1>
<script>
window.onload = function(){
window.navigator.requestMIDIAccess().then(
x => document.getElementById("test-result").innerHTML = "success!",
x => document.getElementById("test-result").innerHTML = "fail!"
);
};
</script>
</body>
</html>
Why does it work locally but not remote?
I am using google-chrome and it is my impression that webmidi should be supported, although experimental https://developer.mozilla.org/en-US/docs/Web/API/MIDIAccess
navigator.requestMIDIAccess() is only available in a secure context, which means your remote host must serve your resources via HTTPS.
Resources served from localhost are considered to be in a secure context, whether delivered via HTTPS or HTTP.
Connect to your remote host using HTTPS instead of HTTP and that should resolve the problem.
I am a beginner in node.js and i tried to set up a HTTP server. I came from web Javascript and i know very little about node.js. I tried a code from nodejs.org, which worked, but when i tried characters like this "á" or "Š", it displayed incorrectly.
I tried using libraries like express.js, it fixed the problem, but i am vanilla - i don't like librariess and it proved difficult for me to even show different pages with different URLs.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Vítejte na mojí webové stránce!');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
The result:
VĂtejte na mojĂ webovĂ© stránce!
What #thomas said: You need to send a header to the browser to tell it which character set to use rendering your text.
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
Some browsers on some host machines may sometimes do the right thing rendering text if you don't do this. But you should not rely on that chance, especially for plain text.
Pro tip: The entire point of nodejs as a platform is to organize your use of good libraries. Node is not a block of wood from which you carve a sculpture, it's a set of lego blocks: really good lego blocks. There's no point in avoiding libraries unless you want to reinvent the flat tire. You can't avoid them: you use the http library already. (Yes, it's built in, but it's still a library.)
It's fine to learn by using minimal libraries. But if you want to actually serve rendered html or files from your file system, you need to use express.
This question already has answers here:
Nodejs HTTP Createserver - unpredictable javascript execution while serving from html files
(1 answer)
Basic static file server in NodeJS
(8 answers)
Closed 4 years ago.
I created the simple server using nodejs and let it call html file which calls iquery. But it does not work with the browser showing the below two errors.
1. "Uncaught SyntaxError: Unexpected token <"
2. "Uncaught ReferenceError: $ is not defined at (index):13"
(Server side code)
var app = require('http').createServer(handler);
var fs = require('fs');
app.listen(1337);
function handler(req, res){
fs.readFile('index_test1.html', function(err, data){
if(err){
res.writeHead(500);
return res.end("Error");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
(index_test1.html code)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo1</title>
<script src="jquery-3.3.1.min.js"></script>
<style type="text/css"></STYLE>
</HEAD>
<BODY>
<p id="test"></p>
<script>
$(function(){
$('#test').text('Hello World!');
});
</script>
</BODY>
</HTML>
jquery-3.3.1.min.js is in the same folder where the server.js and index_test.html exist.
I hope someone help me out on this issue.
Thanks,
There is one interesting thing happening with the code you have written. You are serving one file (index_test1.html) for every request right? Because you have hardcoded it in the handler.
So what is happening is when you're opening localhost:1337 you can see the index_test1.html file.
Now, in that html you import one jQuery file. But guess what, you only have ONE handler and that localhost:1337/jquery-3.3.1.min.js will go through the SAME handler and, YES! YOU GOT IT!, Serve the same exact index_test1.html file.
When you open the server in your browser open the Developer Tools and go to the Network tab. And refresh one more time to see the Network requests. You will see what I am talking about.
What you wanted to do is I guess making a Basic static file server in NodeJS (from #james' comment)? There are very good tutorials to make one out there. But I thought your problem was interesting so I explained it here. Hope this clears up some things for you.
I'm new at nodejs and I want to write to a serial port using node but now I want it to be triggered by a button. And the data is coming from a textbox.
My node script is doing fine when I run it in the console/terminal. But can't do it with a button in a webpage.
Here's my nodejs embedded in html
<!DOCTYPE html>
<html>
<head>
<title>Node x HTML</title>
</head>
<body>
<script>
function write_serial()
{
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});
var text = document.getElementById("textbox1").value;
sp.on('open', function()
{
sp.on('data', function (data)
{
sp.write(name);
});
});
}
</script>
<Input Type = "text" id = "textbox1" >
<BR>
<br><button onclick="write_serial();" href="javascript:;">Go!</button>
</body>
</html>
Here's the error I got when I open the console of the page (F12)
ReferenceError: require is not defined
Thanks in advance for your help. :)
Node.js is a hosting environment, that can execute JS and provides Node.js specific API. Browser, is a different hosting environment, with different API's. You can't use Node's specific API in a browser, and JS that uses Node API will result in an error in a browser.
For example, your script is using global require function, which is not available in a browser API's. And that's why:
ReferenceError: require is not defined
Conversely, your script can't be executed on Node as well, since it uses browser API:
document.getElementById("textbox1")
You've mixed API's from different environments in one script.
However, if your JS script doesn't use Node or browser specific API, it can be executed in both Node and a browser without an error. But it's not the case with your script.
The solution to your problem can be to split your script into two separate scripts, run one in a browser, and the other in Node.js, and to exchange data between them using XMLHttpRequest.
NodeJS is a non-browser JavaScript environment. You can't use most NodeJS features in a browser environment, because they aren't designed for it.
Instead, you'd have a local NodeJS process providing a web endpoint (e.g., a web server; perhaps using Express, but you don't have to) and run that NodeJS process so it's listening for web requests. Then you'd have a button on your web page that makes an ajax call to the NodeJS server, which performs the work.
Naturally, this would only allow you to perform the work on the machine where the server process is running.
Maybe import the serialport module from https://wzrd.in/standalone/serialport#latest
In other hand, try to seperate the logic from the view, i don't know if your app will grow or if it's just a POC, but use a messageBroker or sockets to bind your actions'view with the engine ?
Hope it helps
I am currently using nodejs and express to stream video to tags simply by waiting for app.get on the video tag src address and then using res.writeHead and res.write to provide the data.
I would like to be able to do the something similar but with lower latency using WebRTC. However, I am bit confused as to how to achieve this and haven't really found any good information resource.
Can anyone recommend any good examples, nodejs packages etc... that might be helpful?
I was hoping to do something like:
// Nodejs Server
rtcServer.on('connection', function(connection) {
var videoSource = getVideoDataSource();
videoSource.on('data', function(data) {
connection.write(data);
});
});
rtcServer.listen(8000);
-
// HTML Client
<video src="???:8000"/>