Can't serve javascript file with html - node.js - javascript

I have a webpage with an HTML, CSS, and JS file. It also has one image. I am able to get all of them to function and serve onto the client side, except for the javascript portion. It is most likely a silly syntax thing but I have not been able to solve it.
Here is the code for my .js serving:
else if(req.url === '/index.js'){
console.log("SERVING JS")
res.writeHead(200, {'Content-Type': 'application/json'})
var javaContents = fs.readFileSync('./public/index.js', {encoding: 'UTF8'});
res.write(javaContents);
res.end();
}
^^^ Which is inside my requestHandler function:
function requestHandler(req, res){
}
Before this, I also have:
var http = require('http'), fs = require('fs');
var fs = require('fs');
And I declare my server variable last:
var server = http.createServer(requestHandler);
server.listen(9934, function(){
console.log("== Server is listening on port 9934");
});
I could post all my code but I think that is not necessary. Thank you!

Related

how to read file using fs in node app?

I'm tring to read this file in nodejs using fs module.
I'm getting the response twice. let me know what am i doing wrong. Here's my code.
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile('sample.txt', function(err, sampleData) {
console.log(String(sampleData));
//res.end();
});
console.log("The end");
// res.writeHead(200);
res.end();
}).listen(2000);
After hitting the port in browser. I'm getting the response twice in my terminal. Here's the output.
The end
this is sample text for the testing.
The end
this is sample text for the testing.
You are most likely getting it twice because you are accessing http://localhost:2000/ from the browser.
When doing so there are actually two requests being made. Your actual request and the favicon :) both of which are handled by your server.
Have a look into Chrome debugger -> Network
Two log messages will appear: one for / and one for /favicon.ico
You can verify this by adding console.log(req.url);
To avoid this:
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
if(req.url === '/'){ // or if(req.url != '/faicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
// res.writeHead(200);
}).listen(2000);
A request is made to favicon.io automatically.
To avoid automatic request to favicon, you can do the following
http.createServer(function(req, res){
if(req.url != '/favicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
}).listen(2000);
O/p =>
The end.
this is sample text for the testing.
You may pipe the file to the client:
fs.createReadStream('sample.txt').pipe(res);

node.js won't read and display html file

I'm trying to read and display a basic html file with node.js, but i get no luck, since anything i do it returns the same error.
Here's the code
var http = require('http');
var fs = require('fs');
var url = require('url');
var port = 3000;
fs.readFile('./funckcionalnosti.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
}).listen(3000);
});
The error i get
I've read some things about node not dealing with temporary files, or that my file may not be within current script...i already tried moving files, tried _dirname and copying the entire path name, but it still won't work.
Any help please?

Node.js simplest code not working

As I am a newbie to Node.js and is learning from different articles. So, far I have learnt, my code is
At server side with app.js
var http = require('http');
var app = http.createServer(function(req,res)
{
req.on('end',function()
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello');
});
});
var io = require('socket.io').listen(app);
io.sockets.on('connection',function(socket)
{
socket.emit('connect',{msg:'Hello Client'});
socket.on('client_Says',console.log);
});
app.listen(3000);
At client side with index.html
<script type="text/javascript" src="//localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('//localhost:3000');
socket.on('connect',function(data)
{
alert('Server says '+data.msg);
socket.emit('client_Says',{data:'Hello Server'});
});
</script>
What is that I am doing wrong in above code? When I run app.js in console, it says info - socket.io started but when I run http://localhost:3000 it just keep requesting server.
plus I want to know that is it true that wherever on my pc I create my folder for Node and place app.js and index.html files like above in it and run http://localhost:3000 in browser will automatically make that folder my site folder for localhost after running app.js in Node console?
In your app.js update code to this
var http = require('http'),
fs = require('fs'), //<--- File Module
index = fs.readFileSync(__dirname + '/index.html');
var app = http.createServer(function(req,res)
{
res.writeHead(200, {'Content-Type': 'text/html'}); //<-Updated to text/html
res.end(index); //<---I am sending page
});
Hope that solves your problem
You're not supposed to do this on server side:
socket.emit('connect',{msg:'Hello Client'});
because connect is a default event which is emitted on a successful connection from the server. So when a client connects, the server fires its default 'connect' event, but here you're also triggering your event named connect which might be causing problem.

Node.js how to keep on reading a text file

I'm trying to read a text file. The text file is updated everytime an event occurs in my c program in linux.
Here's my code.
var http = require('http'),
fs = require('fs');
var filetoread = fs.readFileSync('this_is_a_log.txt');
server = http.createServer();
server.on('request', function(req, res){
res.writeHead(200, {'content-type': 'text/html'});
res.end(filetoread);
});
server.listen(9000);
How can node.js continue reading the text file so the page keeps updated everytime the text file is modified. I don't want to use a delay or timeout, I want to do it real time. Is there a function in node.js that can do this. Also I don't want to use tail.

Setting a document root to your Node.js http server?

I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
Use Express or Connect. Examples: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html
For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.
You may add some code to your function like:
var http = require('http'),
io = require('socket.io'),
fs = require('fs'),
server = http.createServer(function(req, res){
// find static image file
if (/\.gif$/.test(req.pathname)) {
fs.read(req.pathname, function(err, data) {
res.writeHead(200, { 'Content-Type': 'image/gif' });
res.end(data);
});
}
else {
// write your div
}
});
server.listen(8080);
I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.

Categories

Resources