Requesting a file with node.js server - javascript

This is the root of the app (http://site.com), that runs when requesting the domain. If I wanted to add only one file say robots.txt (http://site.com/robots.txt) to be requested using this http server, how would I do that? It would pull from the contents of robots.txt and echo it out.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('homepage');
res.end('');
}).listen(process.env.VMC_APP_PORT || 1337, null);
Thanks

Instead of implementing such a functionality manually, you can build your application with http://expressjs.com/ framework and use static middleware documented at http://expressjs.com/guide.html to server static files. But I would personally prefer to put Nginx in front of Node to serve static file, because it has proven to be efficient for this job and it is all about configuration rather than programming then. Configuration can be different depending on the specific purpose and environment, but mine is documented at http://skovalyov.blogspot.com/2012/07/deploy-multiple-node-applications-on.html

Related

Local path referencing when using jQuery.getJSON() method in javascript [duplicate]

I'm running a local copy of nodejs and have taken some code which runs a web service and references a local index.html on startup. This service is running locally on my desktop.
I've been playing about with CSS, and have found no matter what I do, the style sheet does not load, taking the configuration from the style sheet and dropping this within some <style> elements works fine. But for some reason or another, it's not reading the stylesheet.
Location of style sheet is: c:\program files\nodejs\default.css
HTML code:
<link rel="stylesheet" type="text/css" href="default.css" />
This is in the same location as index.js, index.html. Has permissions etc to read file.
Any ideas why this potentially may not be loading.
index.js code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('index.html', function (err, data){
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length' : data.length
});
res.write(data);
res.end();
});
}).listen(1337, '127.0.0.1');
Your server:
http.createServer(function (req, res){
fs.readFile('index.html'
… is configured to ignore everything in the request and always return the contents of index.html.
So when the browser requests the stylesheet it is given index.html.
You need to pay attention to the path (which will be in the request) and serve up appropriate content (which for serving up static files means mapping it onto the file system, determining if the file exists or not, then loading that file or a 404 message), with the appropriate content type (so you'd need to determine that for each kind of file), and status code.
This is a significant chunk of work and not worth reinventing the wheel over so it would probably be best done by finding a static file serving module (Google turns up node-static) for Node (or replacing Node with something like Lighttpd or Apache HTTPD).
If you want to serve up dynamic content as well as static content, then Express is a popular choice (and has support for static files).

Why we need http module installed to run our node js application?

I have found so many sources for now when the first application shows this line
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}).listen(8080);
Just being geek, my Question is why we need server/port to listen our requests for our node js applications?
Why can't we run as localhost/application_name instead?
Why we need that?
Can anyone elobarate please?
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
So if you want an application which only work with bash you don't need any http modules.
Browsers use HTTP. So if you want to develop a web application you need to use that protocol. If you run your project on 80 port you can use it like localhost/my_application.
Simple app.js
var result = doSomething();
functions doSomething(){
return "This the result";
}
console.log(result);
You can call it from bash. node app.js. But it just work and stop.
But if you want to serve this structure to WWW (which is using HTTP) you need to create server. http is a great and simple module for creating servers with node.js.
You can use other js files with using require.
app.js
var result = doSomething();
functions doSomething(){
return "This the result";
}
module.exports = result;
server.js
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var result = require('app.js');
res.end(result);
}).listen(80);
Now you can run your server. node server.js
You can run arbitrary javascript with node. The code you've provided specifically sets up an http server that listens on port 8080. You can reach that webserver from a browser on the same computer by browsing to http://localhost:8080.
We don't need to install 'http' module in order to use it, it is already there in nodejs framework itself.
If you want to see output of any programming language you serve it as http because you want your browser to reach your server. Like what you do it php built in server php -S localhost:8081 or serve it via nginx or apache
If you don't serve your JS, PHP, Python ... over http, browser will treat those files as other unsupported file like a .tar file.
Node is JavaScript environment, Not a web server. You need a server to serve your application. You may use http, https or you can create any other server that can serve your js file.
Well, I do not know if my answer is clear enough to explain but hope you will have some idea why you use http module in your nodejs application.

Communication with an http-server

I have some data that I want to store locally and to be able to pull it dynamically, maybe in another session or after the browser was closed and all browser data was cleared.
I run the site with http-server CLI command and navigate to localhost to access it from the browser.
How can I send data to the server side so the server side will save the data as a file?
I tried to do an ajax post request to see if something happens in the console, but it just returned 404 and nothing came up in the console.
The docs don't mention anything about post requests: https://www.npmjs.com/package/http-server
PS: I have to run this with http-server, this is an offline project.
You will not be able to do this with http-server alone, because http-server can only serve static content and cannot be used to run any code on the server side.
You will have to write a backend yourself, possibly using a framework like Express, Hapi, Restify, Loopback etc. and serve your static files that you need with your new backend, or keep it served as you do now but then you will probably need to take CORS into account if you use different ports for your data saving/retrieving endpoints and your static content - unless you run a reverse proxy that makes it all appear on the same host name and port.
You can use the file system to save the data or you can use a database - either a standalone database like Mongo or Postgres or an embedded database like SQLite or Loki.
For examples on how to serve static content in your own backend see:
How to serve an image using nodejs
You should use express for this kind of stuff. You can easily make methods that handle certain requests.
Here is an exmaple on how to handle a get request by just sending some data
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
And you can use the fs api from node itself to write data.
var fs = require('fs')
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
Note: the fs example uses arrow functions. You can find more information here

How to send a lot of files from server to client using express (NodeJS)

I'm trying to send files from NodeJS server to clients. Many images, css files, js files. For a few files I use
app.get('/js/client.js', function (req, res) {
res.sendFile(path.join(__dirname, '/', 'client.js'));
});
The path is var path = require('path');
So, if I use this construction for every file I want to send, this part of the code will be huge. How can I simplify it?
If you want to serve static content, put all content in public folder in will be automatically served using express.
app.use(express.static( __dirname + "/public"));

how to run node.js on windows with apache server installed in?

I'm a node.js begginer . Let's say I have an apache server(XAAMP) and node.js installed in C:\Program Files\nodejs\nodejs.exe on windows 7.
How can I run node.js in my apache server to simulate my code?
I mean, I know how to write node.js code but what I don't know how it's work on my server?
Apache server don't need for Node.js.
For create your own Node.js server:
Download and install Node.js
Create file hello.js:
var http = require("http");
var server = http.createServer().listen(3000); // beter way for create
server.on("request", function(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
// for view at page http://localhost:3000
res.write("Hello world");
res.end();
});
server.on("listening", function(){
// for view in console
console.log("Listen: 3000...");
});
In terminal go to dir where file hello.js and type:
node hello.js
Open your browser and point it at http://localhost:3000/. This should display a web page that says:
Hello world
A basic HTTP server
Node.js Manual & Documentation
If you like to work with a replacement for XAAMP you should finally take a look at MEAN.io.
At NpmJS.org you will find different solutions for most of your needs.
and like Reagan Gallant commented you should take a look at this famous stackoverflow post (if you need ideas).
NodeSchool indeed is a good entry point for your fist steps. After that npmjs will make sense and finally you will love Mean.io
You just make it use a different port than Apache is using (for example port 3000 which is the default for express-js and others) -- that is assuming that you don't need the two to work together.
If you do need them to work together, you add a forwarding module to Apache and configure the forwarding in Apache of certain URL to go to your local port for node-js

Categories

Resources