i'm developing an application with nodejs. I have to read a local file on server, i'm using this function:
fs.readFile(path, "utf8", function (err,data) {}
how i can serve the 'data' to client? is good to open it in a new tab or downloading it on client.
--UPDATE--
I'm trying to use this solution, too.. is a good way?
res.writeHead(200, {"Content-Type": "application/pdf"});
res.write(data);
res.end();
Assuming you're using some sort of HTTP server here, you'll receive a response object in the handler. This object is actually a stream. I'm using the built-in node HTTP server here for my example.
http.createServer(function(req, res){
fs.createReadStream(path).pipe(res);
});
In express and hapi there is a specific send-file response type if you're using those:
Hapi: reply.file
Express: res.sendFile
Related
I am using node.js to run the server. Always when I make a request to it actually there are occur two requests, one of which is an ordinary one, which was truly made and one is request/favicon.ico. So I tried to send favicon.ico back because I want it to appear in the top bar. But it just doesn`t appear there.
What am I doing wrong? Here is my code:
var http = require("http");
http.createServer(onRequest).listen(7777);
console.log("Server is running now.....");
function onRequest(request, response)
{
console.log("A user made a request" + request.url);
response.writeHead(200, {"Context-Type": "text/plain"});
response.write("Here is some data");
response.end();
}
And I put file favicon.ico into the same folder my server.js is.
This question:Set favicon in HTTP server? is not appropriate for me since the answer and code in answer, which were accepted, for it don`t work for me.
This should work
var http = require("http");
var fs = require("fs");
http.createServer(onRequest).listen(7777);
console.log("Server is running now.....");
function onRequest(request, response)
{
console.log("A user made a request" + request.url);
if (request.url === '/favicon.ico') {
var fileStream = fs.createReadStream("./favicon.ico");
return fileStream.pipe(response);
}
response.writeHead(200, {"Context-Type": "text/plain"});
response.write("Here is some data");
response.end();
}
But as you can see you have to create a special case for each url you want to handle. I recommend using a framework like express which will make things easy for you.
Also with framework you can have favicon in static directory so you won't have to explicitly read from file system on each request for static files.
You can do this by adding this line in your html page in head tag.
<link rel="icon" type="image/png" href=favicon.ico>
If you use http module directly then you will have to inspect the request object on every request and serve the favicon file yourself for all requests requesting favicons.
In your example, you will have to test the request object in the onRequest() function and serve a favicon for some requests, and your original stuff for the rest of the requests.
If you use Express or some other framework with Connect-compatible middleware, then you'll be able to use modules for that like this one:
https://www.npmjs.com/package/serve-favicon
If you want to use just the http module without Express or any other higher level framework, see this answer for examples on how to serve static images with http (and also with Express) that will help you with that:
How to serve an image using nodejs
I need to use the content of files that will be served from the server in the scope of a controller in an angular.js node.js application.
i am using res.sendfile in my node.js to serve a file that is being asked from my client angular.js
now i need to get access to the actual content (text) of the file being served.
this is my code in my client:
$scope.getFile= function(path){
FileService.file.get({filePath: path}, function(data){
//do something with the incoming file
console.log(data);
}, function(err){
console.log(err);
});
}
now for some reason the data that is being sent is returned as an array, so i recieve a huge array with the file content, while i just need the whole content to be inserted into a scope variable for use. what are my options here? should i do something else on my server? or maybe in my client?
is my only option is to actually read the file on the server to stream it as an object back to the client?
it is not possible to return an object with res.sendfile
thanks.
I'm using an AngularJs, node & socket.io to write an app where I want to have some shared data in my different clients. I'm looking at this example: https://github.com/mhevery/angular-node-socketio
I get everything up and running and it works fine if I go to the location of my index.html in my file system (c:/user/angularnodesocket/index.html), but when I go to localhost:8888 the site still shows but the angular stuff is not interpretated.
I get this error on localhost
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/bower_components/angular/angular.js". localhost/:4
Uncaught SyntaxError: Unexpected token < :8888/bower_components/angular/angular.js:1
Can anyone help me with what's going on here?
//G
In that example you are using the following code
http.createServer(function (request, response) {
fs.readFile(__dirname+'/public/index.html', function (err, data) {
if (err) throw err;
response.setHeader("Content-Type", "text/html");
response.end(data);
});
}).listen(8888);
returns index.html whatever the request is. Your browser requests angular.js file, but index html is returned instead which causes the error messages you see.
You have to modify server.js code to support static files.
I'm used to apache and putting configuration items in httpd.conf
Where do these types of configurations go in a node environment. For example, I want to make sure that only GET, POST, and PUT are accepted and Head and Trace are not accepted. Where does a config like that go?
Additional things like Cache-Control and limiting request and response sizes.
Node.js is just a JS framework with a system API. Technically, you could reimplement Apache HTTP Server in Node.js, mimicking its behaviour and its configuration structure. But would you?
I believe you are using Node.js' HTTP module. Look at the docs: there's no way to read configuration from a file. The server is programmatically created using http.createServer. You provide a callback that listens to requests. This callback provides an http.IncomingMessage parameter (first parameter) which contains everything you need.
Here's an example:
// load the module
var http = require('http');
// create the HTTP server
var server = http.createServer(function(request, response) {
// use the "request" object to know everything about the request
console.log('got request!');
// method ('GET', 'POST', 'PUT, etc.):
console.log('HTTP method: ' + request.method);
// URL:
console.log('HTTP URL: ' + request.url);
// headers:
console.log('HTTP headers follow:');
console.log(request.headers);
// client address:
console.log('client address: ' + request.socket.address().address);
});
// listen on port 8000
server.listen(8000);
If you really want a configuration file, you will have to forge it yourself. I suggest creating a JSON configuration file as this can be turned directly into a JS object using JSON.parse(). Then just use your configuration object programmatically to achieve what you want.
I have made a couchdb design document which works perfectly on the following url
http://localhost:5984/db/_design/app/index.html
Now the problem is i am trying to fetch the page contents and display it from node js but only the html page is displayed the linked css and js files are not working and when i tried to narrow down the problem i found that the css and js files are suppose to have the login credentials of the couchdb and is not linking I even tried adding the auth header in the response parameter but still no luck
var http = require('http');
var json;
var root = new Buffer("admin:pass").toString('base64');
http.createServer(function(req, res) {
res.setHeader('Authorization', root);
res.writeHead(200, { 'Content-Type':'text/html' });
couchPage();
res.end(json);
}).listen(8080);
function couchPage() {
var options = {
hostname: 'localhost',
port: 5984,
path: '/db/_design/app/index.html',
auth: 'admin:pass',
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
json = chunk;
});
});
req.end();
}
could any one please guide me where am i wrong
I think this has nothing to do with couchdb authorization. The problem is that you do not perform any routing on your nodejs server. That is, the browser makes a request to localhost:8080 and receives the content of /db/_design/app/index.html as an answer. Now, the browser detects a link to a stylesheet, say "style.css". It performs a request to localhost:8080/style.css but your nodejs server simply ignores the "style.css" part of the request. Instead, the client will receive the content of /db/_design/app/index.html again!
If you want to serve attachments of your design document through nodejs, you have to parse the request first and then retrieve the corresponding document from couchdb. However, I don't think that you actually want to do this. Either you want to use couchdb in a traditional way behind nodejs (not directly accessible from the client) and then you would just use it as a database with your html (or template) files stored on disk. Or you want to directly expose couchdb to the client and make nodejs listen to events via the couchdb _changes feed.