Node.js: Sending file in same directory - linux

I hope this question isn't too ridiculous.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req,res){
res.sendFile('index.html');
});
http.listen(3000,function(){
console.log('/','listening on *:3000');
});
I am running linux mint, and whenever I try to run this locally I get the following error:
Error: ENOENT, stat 'index.html'
at Error (native)
I believe it has something to do with the directory. The index.html file is in the same folder as the index.js file. I've searched around and couldn't find this exact error in this case so am kind of confused. Am I putting in the wrong directory for the
app.get('/', function(req,res){
res.sendFile('index.html');
});

You need to specify exactly where your index.html file is located. Try using the following code snippet
var app = require('express')();
var http = require('http').Server(app);
var path = require('path');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname, 'index.html'));
});
http.listen(3000,function(){
console.log('/','listening on *:3000');
});

Related

node.js what is causing error 400 bad request

I was adding some code to my node.js web app. I added this one feature, and then it threw an error 400. I removed it by hitting Ctrl-Z, but it still threw error 400. Then, I made a test.js that was the simplest implementation of express, and it is still getting error 400. Here is my code for test.js:
const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');
app.get("/", function(req, res)
{
res.sendFile(__dirname + "/test.html");
});
http.listen(3001, function()
{
console.log("--listening on port 3001");
});
I have checked to make sure I am typing in the correct url, with the correct port. I think something got cached and is screwing it up, since it works if I clear my cache or use curl. Any ideas?
Use process.cwd() instead of __dirname which is causing error and generating 404.
process.cwd() will return the directory where node is intialized. It returns absolute path where you started the node.js process.
const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');
const path = require('path');
app.get("/", function(req, res)
{
// res.sendFile(__dirname + "/test.html");
res.sendFile(process.cwd() + "/test.html");
});
http.listen(3001, function()
{
console.log("--listening on port 3001");
});
or You can also resolve the path of __dirname
const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');
const path = require('path');
app.get("/", function(req, res)
{
__dirname=path.resolve();
res.sendFile(__dirname + "/test.html");
});
http.listen(3001, function()
{
console.log("--listening on port 3001");
});
After some more research (and thanks to comments), I finally found the problem!
I was storing too much stuff in cookies, and it exceeded the maximum amount of 4KB.

Multiple routes for static html pages in Express

I am trying to serve 2 static HTML pages from Express but whilst the index.html is correctly served I get an error when I try to access the /about route:
Error: ENOENT: no such file or directory, stat
'/var/www/html/myapp/about.html'
at Error (native)
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/html_files'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/about', function(req, res) {
res.sendfile(__dirname + '/about.html');
});
app.listen(3000);
I can update the '/about.html' to '/html_files/about.html' and then it works but whilst this solves the issue I can't understand why it wouldn't work as it is.
Looks correct.
app.get('/'... will be ignored, as server already has found static index.html matching this request.
app.get('/about'... fails because of incorrect url to file you're trying to send. If you ask for /about.html it'll be sent by static middleware correctly.

Nodejs: Path must be a string. Received null

I was trying to implement the following code and got the TypeError error when I ran it.
app.js
var app = module.exports = require('express').createServer();
var io = require('socket.io').listen(app);
var path = require('path');
app.listen(3000);
app.get('/',function(req,res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.emit('welcome', {text: 'Welcome!!!'});
});
Error Output:
TypeError: Path must be a string. Received null
at assertPath (path.js:8:11)
at posix.join (path.js:479:5)
at exports.send (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/node_modules/connect/lib/middleware/static.js:129:20)
at ServerResponse.res.sendfile (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/response.js:186:3)
at /Users/rluo/Desktop/learn/learnNode/socket.io_epxress/app.js:8:6
at callbacks (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:272:11)
at param (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:280:5)
at Object.Router.middleware [as handle] (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:45:10)
package.json:
{
"name":"socketio_express-example",
"version":"0.0.1",
"private":true,
"dependencies":{
"socket.io":"0.8.7",
"express":"2.5.4"
}
}
Thanks in advance.
The error is pretty clear, you need to specify an absolute (instead of relative) path
Examples:
// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');
You do not need path at all
Global Objects
__dirname
Added in: v0.1.27
The name of the directory that the currently executing script resides in.for more detail https://nodejs.org/docs/latest/api/globals.html
check this thread TypeError: Path must be a string
Creating socket
var app = require('express')();
var http = require('http').Server(app);
Express initializes app to be a function handler that you can supply to an HTTP server (as seen in line 2).
socket.io
__dirname vs path
Before you use res.sendFile() you need to set static files directory like below.
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname+'your index or static files location'));
app.get('/',function(req,res){
res.sendFile(__dirname+'index.html');
});
Please use the 'path' module that you have required. Try this:
app.get('/',function(req,res){
res.sendfile(path.join(__dirname, '/index.html'));
});

nodejs express apps in small orange

I am new to "A Small Orange" and I am trying to run an express app in small orange following this link
I first created the following directory structure
/home/user/servercode/myapp with tmp directory and app.js file
/home/user/public_html/clientCode/myapp with .htaccess
/home/user/servercode/myapp/tmp contains an empty restart.txt file
In /home/user/servercode/myapp, I ran
npm init
npm install express --save
This is my app.js. Pretty much same as the one in the link mentioned in the post
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World Express App');
});
if (typeof(PhusionPassenger) != 'undefined') {
console.log( 'Example app listening with passenger' );
app.listen('passenger');
} else {
console.log( 'Example app listening with 3000' );
app.listen(3000);
}
.htaccess has 644 permission level and contains this
PassengerEnabled on
PassengerAppRoot /home/user/serverCode/myapp
SetEnv NODE_ENV production
SetEnv NODE_PATH /usr/lib/node_modules
When I try to access myapp, I get this error
Cannot GET /myapp/ and 404 in browser console
I could get a normal nodejs application running without express with the below content in app.js
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
But not able to get express app running
You need to add route in you application as :
app.get('/myapp', function(req, res){...});

Node-Server wrong directory in loading Template via Express

I have some problems when running my Node-Server on Remote via an Service.
I get the following Error:
Error: Failed to lookup view "index" in views directory
"/home/naoufal/etc/run-nodeServer/views" at EventEmitter.render
(/var/www/virtual/naoufal/html/node_modules/express/lib/application.js:579:17)
He looks for my Templatefolder in the path, where the Servicescript is started, namely (/home/naoufal/etc/run-nodeServer/...)
My Node-Application is on (~/html/...).
var express = require('express');
var app = express();
var ECT = require('ect');
var ectRenderer = ECT({watch: true, root: __dirname + '/views',ext: '.ect'});
app.set('view engine','ect');
app.engine('ect',ectRenderer.render);
app.get('/',function(req, res){
res.render('index');
});
app.listen(68000);
I tried instead of ('__dirname + '/views')
This '/home/naoufal/html/views' but the same error occurs...
Any suggestions?
ok I found the solution:
app.get('/',function(req, res){
res.render('index');
});
Here he did not use the right Path, from the Renderer. I don't know why? Instead it takes the path of the executing script...
app.get('/',function(req, res){
res.render(__dirname + '/views/index');
});
solved the problem anyway.

Resources