I'm trying to display the content of a html file into node js file using readFileSync(). But I get this error :
Error: ENOENT, no such file or directory 'index.html'
at Object.fs.openSync (fs.js:427:18)
at Object.fs.readFileSync (fs.js:284:15)
at port (/app/web.js:6:22)
at callbacks (/app/node_modules/express/lib/router/index.js:161:37)
at param (/app/node_modules/express/lib/router/index.js:135:11)
at pass (/app/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/app/node_modules/express/lib/router/index.js:170:5)
at Object.router (/app/node_modules/express/lib/router/index.js:33:10)
at next (/app/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.expressInit [as handle] (/app/node_modules/express/lib/middleware.js:30:5)
Here is my web.js file:
var express = require('express');
var app = express.createServer(express.logger());
var fs=require('fs');
app.get('/', function(request, response) {
// response.send('Hello World2 !');
response.send(fs.readFileSync('index.html').toString());
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
The "web.js" file and the "index.html" are in my github repository in the following address:
https://github.com/myUsername/bitstarter/blob/master/node-js-sample/web.js
https://github.com/myUsername/bitstarter/blob/master/node-js-sample/index.html
I tried different paths to address "index.html" none worked, such as
/bitstarter/blob/master/node-js-sample/index.html
/node-js-sample/index.html
/bitstarter/node-js-sample/index.html
./index.html
!
I'm using AWS EC2 ubuntun 12-4.
I've been straggling with this error for hours! Any help is highly appreciated.
The line that says app.get('/', ... means "when the client asks for '/'..." That is: it maps "web space" (URL paths) into actions. In your case -- read and return the contents of index.html.
So the proper request in your case is just www.mydomain.com/.
If you want to be able to serve static files, read up on express.static()
As Nitzan mentioned, in the long run you will want to learn how to use express.static() to serve html files and templates as you build out your node app. In response to your present question, however, I recommend the following:
Save the index.html file into the same directory as your web.js file in you EC2 instance (i.e. don't try to remotely access it on your github page).
Use the following code:
var content = fs.readFileSync('index.html', 'utf-8');
response.send(content);
This will read the contents of your index.html file into a variable called content while specifying the proper encoding. Then it will instruct node to send the content to the browser.
The problem appears to be that you are not adding "index.html" in git. Fist you need to add this to git and then push to heroku. This will solve your problem. Hope it helps :)
Related
I am new in programming and face static file serving problem. I followed my tutor properly but still face the problem. This is the server file named app.js from where I want to serve the js file named index.js in the static directory
const express = require('express');
const app = express();
const port = 3000;
app.use('/static' , express.static('static'));
app.get('/', (req, res)=>{
res.send('This is a page of website');
})
app.listen(3000 , ()=>{
console.log(`The application is running at port ${port}`)
})
And I made a directory named static in which I made a file index.js with some js contents.
The tutor then runs the terminal with node ./app.js and in the browser, he searches for the URL as localhost/static/index.js and he was served with the js file as a static file but for me, it shows the site can't be reached. Considering there is no issue in my node.js processing.
Actually, the problem was the URL search. As you know that for localhost if you are running the server at port 80 it does not require writing the port. But since I used port 3000 and I do not mention the port in the URL that is why it shows me the site cant be reached and my tutor was using port 80 and me 3000.
I believe the issue could be that you forgot to add the port to the URL. Your server is listening on port 3000, so you need to search for 'http://localhost:3000/static/index.js'.
one more solution is it here. If the name of the Html file inside the public folder is different from index.html so this is also not work. so first set folder name index.html and then connect your index.js folder to html file ,then run server.you are definitely gets the results .
i am also a psuedo programmer if any mistakes please forgive me.
thank you.
I want to deploy an application that I perform with the MEAN stack on Heroku, but I encounter 1 problem.
I have this folder structure, my node server, with a public folder, where is the dist / fronted folder and all the files generated by Angular's ng build --prod, it works when I start the server and browse normally, but if I refresh the page or write a route myself, I get these errors:
Errores
Sorry for my English.
If your are building a MEAN stack, you probably have a server.js or index.js or app.js as an entry point to your application. An SPA by definition manages all the routes within the router configuration. But if you try to refresh or type a route yourself, it is like you were trying to access that folder on the server (ex: www.mywebsite.com/about, here the folder about might not exist on the server, it is just known by your Angular app)
My suggestion is that you try to add this fix to the app.js (or server.js or app.js) file, so all unexisting routes or refresh go back to your index.html:
// Check your port is correctly set:
const port = process.env.PORT || 8080;
// Is saying express to put everything on the dist folder under root directory
// Check the folder to fit your project architecture
app.use(express.static(__dirname + "/dist"));
// RegEx saying "capture all routes typen directly into the browser"
app.get(/.*/, function(req, res) {
// Because it is a SPA, all unknown routes will redirect to index.html
res.sendFile(__dirname + "/dist/index.html");
});
app.listen(port);
This guy shows full deploy on Heroku with Angular: https://www.youtube.com/watch?v=cBfcbb07Tqk
Hope it works for you!
I'm sorry to ask such a simple question. I've been sent files by someone, an index.html file which pulls in a js file within script tags. I have to start a webserver to get through authentication and view the files (am in dev).
In my CLI i have navigated to the directory containing index.html. I have checked with node -v that I have it installed globally (yes, v 8.6). I've run the simple command node and checked my browser at http://localhost:3000 and a few other ports but get no joy. I've also tried node index.html but CLI throws an error.
How do i start the webserver? All the examples online tell me to build a .js file, but this is not an option.
Steps to set up a node web server
Create the route folder from your local machine.
Go to the command prompt from the project root path.
Install express using the command npm install express
Create server.js file
create the folder wwww and create the Index.html inside it.
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/www'));
app.listen('3000');
console.log('working on 3000');
Index.html
<!doctype html
<html>
<head>
<title> my local server </title>
</head>
<body>
<h1> server working </h1>
<p> just put your html,css, js files here and it work on your own local nodejs server </p>
</body>
</html>
Go to the project root path and take the command prompt, then start the server by running the command node server.js
Then go to the browser and run the url localhost:3000.
Now you can see the html page will render on your browser.
Since you don't want to build a backend but just an http server.
I would propose to use an npm package that do just what you need:
Open a console
npm install http-server -g
Go to your "index.html" folder (in the console) then type:
http-server
Then reach your content in your browser at this address:
http://localhost:8080
Documentation here:
https://www.npmjs.com/package/http-server
Yes, this is possible.
A very simple example of how to do this would be to create file, let's call it app.js and put this in it:
const http = require('http'), // to listen to http requests
fs = require('fs'); // to read from the filesystem
const app = http.createServer((req,res) => {
// status should be 'ok'
res.writeHead(200);
// read index.html from the filesystem,
// and return in the body of the response
res.end(fs.readFileSync("index.html"));
});
app.listen(3000); // listen on 3000
Now, run node app.js
Browse to http://localhost:3000
There's loads of other npm packages that will help you out do this, but this is the simplest 'pure node' example to literally read index.html and serve it back as the response.
Its very easy to start a server using node js
Create a server.js file,
const http = require('http')
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(3000);
Run node server.js
Here is a reference
This will even solve your backslash issue by this
I am new to node.js, and I am trying to use the serveStatic function to locate a specific file.
When I specify the exact path in the argument it doesn't work. However it works only when I specify the directory only , and name the file index.html inside that directory.
Any idea on how I can use to it locate a specific file? Any help would be really appreciated from you guys thanks!
Below is my code
var connect = require('connect'),
http = require('http'),
serveStatic = require('serve-static');
var app = connect();
// app.use(serveStatic('public')); Works
app.use(serveStatic('public/test.html'));// doesn't work
app.use(function(req, res){
});
http.createServer(app).listen(3000);
serve-static is meant to serve a whole directory (with all sub-directories, if any). You can't use it to serve just one single file.
What you could do with serve-static is to set a default file to be sent when user requests a root of your directory (by default it's an index.html file):
app.use(serveStatic('public', {index: 'test.html'}));
But if you really want to send just a single file, then is's better to use this answer:
app.use(function(req, res) {
res.sendfile('test.html', {
root: __dirname + '/public/'
});
});
Though, the best possible solution is to read this file once and cache it. In this case there will be no need to access your storage device each time somebody is requesting this file:
var html_data = require('fs').readFileSync('./public/test.html');
app.use(function(req, res) {
res.send(html_data);
});
This is my first time with node.js. I get it to display the index.html, but it doesn't display the images on the site or anything else, it ONLY shows the basic html stuff. Here's how I set it up.
There's no apache, php or anything else on the server, just ubuntu, proftp and node(and curl and the other dependencies). I made the main directory for the node files /var/nodeFiles and the directory for the html/site files is /var/nodeFiles/www
so for my node server file I did it like this:
var http = require('http'),
fs = require('fs');
fs.readFile('/var/nodeFiles/www/index.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(80);
});
this works, but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display. The files and directories are all correct, I've double checked and the permissions of the folders are correct. So what else do I have to do to get node to display the rest of the site?
I hope I've explained my self correctly, I was told this is the place to ask development questions.
Thank you for taking the time to read this.
but it ONLY shows the index.html file and NOTHING attached to it, so no images,
no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
Check this basic code to setup html server. its work for me.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.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(8000);
});
This did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
Update 1/28/2014:
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
End Update
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$#"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
You can simply use
res.senFile('PATH_TO_FILE');