create a web server for local html using node - javascript

I'm tring to create a simple web server to run my local html file, and now I can get a server running on localhost using code below
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html', 'utf8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(3000);
But there is a problem that every time I changed my html file, the web page on localhost is still the old one, I need to restart the server to make the changes visible.
I want to improve that and I tried to use koa or express, like code below
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Application started and Listening on port 3000");
});
app.get("/", (req, res) => {
res.sendFile("test.html");
});
And I found that express can serve real-time html files, I don't need to restart serve when files change.
How can I use http moudle to achieve that?

Currently you read the file when the program starts up. Then each time you get a request you serve up the data from the variable.
Move that code inside the callback function that runs when you get a request, then it will be updated each time a request comes in.
http.createServer(function (req, res) {
var index = fs.readFileSync('index.html', 'utf8');
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(3000);
You could avoid reading the file on each request by having the variable outside the function (as in your original code) and watching the file for changes (and updating the variable in response).
That said, using Express and its static module will provide benefits with caching and I'd recommend it over rolling your own.

You can use nodemon.
npm install -g nodemon
nodemon server.js

Related

ngrok Cannot GET / local server up and running

I'm trying to follow Crowdbotics' Messenger bot tutorial, however. I did exactly as he mentioned but i am getting this.
My folder:
Okay so, first of all i run node index.js and get the following:
Right after that. We initialize our ngrok server by ngrok http 5000 and get the following:
But on EVERY http request i get the classic Cannot GET /.
On the hindsight, my index.js only contain:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(5000, () => console.log('Webhook server is listening, port 5000'));
I can't really point out what i am doing wrong, your help is truly appreciated.
Based on your express js code, I think you haven't define the routes to '/'
add this before the app.listen on the index.js file
app.get('/', (req, res) => res.send('Hello World!'))
Your index.js has started a server that listens and respond to the HTTP protocol - but it does not "serve files" the same way a web server such as Apache does.
As #Yana notes, you need to explicitly set a route to do something, such as send a text response back.
If you want the favicon.ico file to be sent when requested, then you need to setup a static route for that as part of your index.js code.

Using a node.js app with HTML

My goal is this: JS but server-side. My solution, the obvious, node.js. I've used node.js quiet a bit. Mainly for an application, not a web server. The only reason I need to do server-side JS is that I need to use a library that connects to the Discord API. So I have a little test .js file with my node.js in it. It just prints text if it works. Basic. What I need it to do is whenever someone goes to https://example.com/something, it runs the node.js script and if the script ends up with printing "hello", then https://example.com/something will say "hello".
I've done some research on this, I've found ways to deploy a node.js app, which I know how to do. I can't really find anything that I'm looking for though.
You can use express to run a webserver on nodejs
Install express by running "npm install express" in your project folder through command prompt
Create a app.js file with the following code
var express = require('express'); // load the express library
var app = express(); // create an instance of express
var child_process = require('child_process'); //load the child_process module
app.get("/something", function(req, res) { // Setup a router which listens to the site http://localhost/something
child_process.fork("./yourCodeFile.js"); // Launch your code file
});
app.listen(80);
Run node app.js to listen to web connections
Then you put your code into the yourCodeFile.js which has to be be in the same folder as the app.js file, even better you could just write all your code in the app.js code as long as you keep it inside the function inside app.get
You should take a look at cloud-based lambda functions and platforms like AWS Lambda, which run a script in response to an HTTP request. They are relatively new and the architecture used to support this is being called "serverless", which is a simple term, albeit a bit of a misnomer. There are various tools out there to help you build these systems, such as the similarly named Serverless framework, though you can typically still use more traditional server frameworks that you are probably more comfortable with. Either way, you are not responsible for managing any server, including starting it or stopping it.
In terms of constructing a response that you are happy with, you can of course respond with any arbitrary string you want. See the AWS example of a Node.js handler.
exports.myHandler = function(event, context, callback) {
callback(null, "Hello, world!");
}
Lambda functions can also return binary data and work well with static storage systems like Amazon S3. For example, the function can be run in response to the creation of static assets.
Your code should look like this:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const pathName =url.parse(req.url).pathname;
if (pathName == '/something') {
res.end('Hello World\n');
} else {
res.end('Please visit /something \n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You should run your file with node youfile.js And when you do curl http://127.0.0.1:3000 you will see
Please visit /something
But when you do curl http://127.0.0.1:3000/something you will see
Hello World

How to run a website developed with node.js in local?

I would like to run a website developed with node.js in local.
I already installed node.js but when I lauch a .js file on my terminal, nothing happen ( $ node file.js )
Also, I guess I have to simulate a server ? How can I do that with node?
You can start a simple server with the example that can be found on nodejs.org:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
https://nodejs.org/en/about/
To develop a website it is very helpful to use a web framework such as Express.
http://expressjs.com/
You should use:
npm start file.js
but also be sure to check out nodemon, which is very helpful for debugging - it restarts your app on code change.
Also be sure to check out the express generator, which will set up a node+express app that you can check out to figure how to get the server and routes going.

Node.js: cannot get json object on localhost

I have an android app that is going to send a json to my server where I will have a node.js express app. Meanwhile, I want to test it on my localhost.
On my android code I send the json to:
new HttpAsyncTask().execute("http://10.0.2.2:8080/ReceiveJson");
This code is triggered by a button and is working fine.
Then in my app.js file I have the following code:
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 8080);
app.get('/ReceiveJson', function(req, res) {
console.log(req.body);
res.send(req.body);
res.json(req.body);
res.send("ok");
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In my terminal I run node app.js and I get just the answer "Express server is listening on port 8080". Nothing else.
When I go to my browser and put
http://localhost:8080/ReceiveJson
I get "{}" as an answer.
In my terminal I get the same answer.
What do I have to do to receive the json?
Thanks
That's because you are responding with the req.body:
res.send(req.body);
The code below it never gets called because you have already responded:
res.json(req.body);
res.send("ok");
Because you are using a web browser, there is nothing being sent in the body because it is a get request and there will be nothing in the body for a get request, therefore you get an empty json object, hence {}.
If you change your code to:
app.get('/ReceiveJson', function(req, res) {
res.send("ok");
});
Then when you browse there in your browser you will get the response 'ok'
If you are looking to post or put to your express server then you need to use either app.post or app.put. I noticed that you are trying to send JSON with an Android device for an app you have already written. I would highly recommend using Fiddler or something to test with, just make sure that when you send JSON to your express app you are using the header:
Content-Type: application/json
EDIT:
Your JSON might not be working because you aren't using the body parser. Try inserting this in your code before app.listen
app.configure(function(){
app.use(express.bodyParser());
})

Node.js on a remote server: io is not defined

I'm building an application that links to a node.js hosted on my home computer (78.233.79.103:8000)
The server is properly istalled (if you go to the addres I gave you'll se the socket.io works)
If I run the server in localhost with
node server.js
all is good, the application works
Then when I run the application on my other pc or on my iPad (I wrapped it with phoneGap so it's just a web app included in a native iOS app), trying to connect the io on 78.233.79.103:8000 i got the console log:
io is not defined
here is my sourcecode: https://github.com/synbioz/puissance4
look for the server.js
I know I only call io = require('socket.io').listen(PORT); but kwnow also I should create something like:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000, '78.233.79.103');
that actually doesn't works
Any idea?
probably because .listen() doesn't return this.
try writing them in separate lines.
var io = require('socket.io');
io.listen(PORT);

Categories

Resources