NodeJS Error: Can't Find Variable: require - javascript

I am working with a NodeJS server that hosts a website and a Javascript program. Most of the javascript works fine, but I am running into an error now with one of the npm modules that isn't able to be "required".
I'm getting an error from the inspector console that:
ReferenceError: Can't find variable: require
I am not sure what's happening here, as from what I can tell the server should have access to these public modules. Here is the server code:
var fs = require('fs');
var http = require('http');
http.createServer(function(request, response) {
if(request.url === "/Users/christophermartone/Desktop/Programing/resturauntApp/driver.js") {
var file = fs.createReadStream('driver.js');
file.pipe(response);
console.log("Made it to JS");
response.writeHead(200, {'Content-Type': 'text/javascript'});
}
else {
var file = fs.createReadStream('index.V1.0.html');
console.log("Made it to HTML");
file.pipe(response);
response.writeHead(200, {'Content-Type': 'text/html'});
}
}).listen(8080);
I found some documentation that suggested I should do npm link #Source/Module... which I did, but the issue is still not resolved.
Am I missing something in the server script? Or is there an extra step I am missing?
I can provide the full html and javascript code if needed, but the issue does not appear to be with them, only when they are running on the Node server.

Related

html page not loading when running javascript server

So I'm creating a game with HTML, css, and javascript, and I'm trying to incorporate template engines/ajax in this task. I made a server which if I run in cmd and then open up google chrome and type 'localhost:3000' in the address line, it is supposed to direct me to the main.html page.
However, when I type 'node server.js' in cmd, it runs properly but when I enter 'localhost:3000' in the browser it says the page does not exist. I'm not sure what went wrong. If I were to manually double click on the html file in my folder, it works, but I'm trying to get it to load by running a server.
I have three folders (img, node_modules, and pages) and 2 json packages which were created by installing express and pug. It's hard to explain my folder paths and code here, so I have a link to a folder containing my files/sub folders and it also gives a clearer view of the path in my directory: https://github.com/jessaisreal/game
It wouldn't let me upload the node_modules folder as it was too big, but I automatically got it from typing 'npm init', 'npm install express' and 'npm install pug' into the cmd line in the folder.
I'm assuming something is wrong with my server.js file or the way my folders are set up. I'm really desperate to get my program working and would appreciate any help. I have no idea why my html page isn't loading. I'm also not sure if I handled the GET request for getting specific fonts correctly.
I cut down my program as much as I could. There are several html and css files, but only included create and main here for simplicity. Again, I would appreciate any help or a push in the right direction!!
server.js:
const http = require('http');
const fs = require("fs");
const pug = require("pug");
//user pug functrion to render through the create Page
const renderMain = pug.compileFile('pages/main.pug');
const renderCreate = pug.compileFile('pages/create.pug');
//Helper function to send a 404 error
function send404(response){
response.statusCode = 404;
response.write("Unknown resource.");
response.end();
}
// Helper function to send 500 server error;
function send500(response){
response.statusCode = 500;
response.write("Server error.");
response.end();
}
// initilize the server
const server = http.createServer(function (request, response) {
//console.log(request.method+" -> "+request.url); test about the income request
// handle the get request
if(request.method === "GET"){
if(request.url === "/" || request.url === "/main"){
let data = renderHome("./pages/main.pug",{})
response.statusCode = 200;
response.end(data);
}else if(request.url === "/main.js"){
//read main.js file and send it back
fs.readFile("main.js", function(err, data){
if(err){
send500(response);
return;
}
response.statusCode = 200;
response.setHeader("Content-Type", "application/javascript");
response.write(data);
response.end();
});
}else if(request.url === "/main.css"){
//read css file
fs.readFile("main.css", function(err, data){
if(err){
send500(response);
return;
}
response.statusCode = 200;
response.setHeader("Content-Type", "text/css");
response.write(data);
response.end();
});
}else{
send404(response);
return;
}
}
});
//Server listens on port 3000
server.listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
I highly suggest that you use expressjs for better organizing your project and this issue will be gone

running into node.js TypeError: First argument must be a string or Buffer with the simplest possible script

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 Error EADDRINUSE and HTML file not rendering, instead shows html codes

I'm new kid on the block with NodeJS. Right now im following a basic tutorial of NodeJS, so far so good.
But I have a problem using fs.createReadStream method:.
var http = require("http");
var fs = require("fs");
function fourOHfour(response) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("four oh four.....");
response.end();
}
function onRequest (request, response) {
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/plain"});
fs.createReadStream("./index.html").pipe(response);
}
else{
fourOHfour(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("server is running......");
When I go on my browser and type localhost:8888, it should be rendering the index.html file in HTML but the result is wrong, all I get is a bunch of codes of index.html file - plain text.
Meanwhile in my sublime compiler, I've got no error in regards to this case. Until i try to edit my code, whatever I cahnge, it will give me an error like this:
If that thing happen, I cant fix the error unless I restart the laptop, then everything running well again. At least my compiler say that the server is running... Even thought my localhost:8888 still not rendering the HTML file.
You are specifying your content type as: text/plain which means the page will not render in HTML but instead, plain text. This is why you see the "codes" from your HTML file instead of the actual HTML being rendered.
To fix that problem, set the content type to text/html like so:
response.writeHeader(200, {"Content-Type": "text/html"});
In regards to the error you posted, "EADDRINUSE"
EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.
So, in your case, there must be running a server on port 8888 already.
Check for the listening event like this, to see if the server is really listening:
var http=require('http');
var server=http.createServer(function(req,res){
res.end('test');
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(8888);
EADDRINUSE - seems like port is busy by another process or maybe by same nodejs process that don't want to close.
try to kill process:
killall node
about code - try this:
var http = require("http"),
fs = require("fs"),
URL = require('url');
function output(response, body, status) {
status = status || 200;
response.writeHead(status, {"Content-Type": "text/html"});
response.end(body);
}
function fourOHfour(response) {
output(response, 404, "four oh four...");
}
function onRequest (request, response) {
var uri = URL.parse(request.url).pathname; // extractin URI part
var method = request.method || 'GET'; // detecting method otherwise GET
if(method == 'GET' && uri == '/'){
// reading file
fs.readFile(__dirname+'/index.html', function(err, data) {
if(err) { // if error happen, output error
output(response, err, 500);
return;
}
output(response, data); // ouput html body
});
return;
}
fourOHfour(response);
}
var httpServer = http.createServer();
httpServer.on('request', onRequest);
httpServer.listen(8888);
To run Your code in production do following in terminal:
install forever:
sudo npm install -g forever # remove sudo word if You use windows, or You're already root user
start app using forever:
forever start app.js
To run Your code in development environment:
install nodemon:
sudo npm install -g nodemon # remove sudo word if You use windows, or You're already root user
run Your app using nodemon:
nodemon app.js
Forever will keep Your app running and will output logs which You can see using:
forever list # lists running processes
forever logs # shows logs that outputs forever
forever logs 0 # read logs of 0-th process
To restart forever process:
forever restartall # restarts all forever instances
forever restart 0 # restarts first process
To stop:
forever stopall
forever stop 0
About Nodemon: it's a tool that watches changes in Your file and restarts it automatically, no need to stop-start Your app, so that's why I prefer nodemon in dev environment

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.

NodeJS - "This type of response MUST not have a body..."

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.

Categories

Resources