How to load webpage as response to request - javascript

I would like to load a webpage in response to a request for a path,I have figured it out till here:
var http=require('http');
var mysql=require('./mysql');
var fs=require('fs');
var app=http.createServer();
app.listen(8000);
app.on('request',function(req,res){
var _path=req.url;
if(path==='/')
{ res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello World \n');
}
if(path==='/demo')
{
//this is bad,we could use streams to improve this(although this is non-blocking too)
fs.readFile('../maps/google_maps.html',function(err,contents){
if(err)
{
console.log('did not work');
res.writeHead(500);
}
else
{
res.setHeader("Content-Length", contents.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.write(contents);
}
res.end();
});
}
});
Server does not work for /demo path,it throws the error:
{ [Error: ENOENT, open '../maps/google_maps.html'] errno: 34, code: 'ENOENT', path: '../maps/google_maps.html' }

var _path=req.url;
if(path==='/')
you create _path but then compare path, which is always undefined
change it to var path=req.url;
error:
ENOENT means file not found
../maps/google_maps.html is a path relative to where you're calling node from, so make sure file exists, or specify full path
To make a path relative to the script, you must use the __dirname variable.
__dirname + '/path/to/file'

You should better use Express.js along with Jade which is a templating engine for Node.js. You can easily render html pages to client and serve static content

Related

Setting the correct content-type in HTML web browser [duplicate]

I have a logo that is residing at the public/images/logo.gif. Here is my nodejs code.
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end('Hello World \n');
}).listen(8080, '127.0.0.1');
It works but when I request for localhost:8080/logo.gif then I obviously don't get the logo.
What changes I need to do to serve an image.
2016 Update
Examples with Express and without Express that actually work
This question is over 5 years old but every answer has some problems.
TL;DR
Scroll down for examples to serve an image with:
express.static
express
connect
http
net
All of the examples are also on GitHub: https://github.com/rsp/node-static-http-servers
Test results are available on Travis: https://travis-ci.org/rsp/node-static-http-servers
Introduction
After over 5 years since this question was asked there is only one correct answer by generalhenry but even though that answer has no problems with the code, it seems to have some problems with reception. It was commented that it "doesn't explain much other than how to rely on someone else to get the job done" and the fact how many people have voted this comment up clearly shows that a lot of things need clarification.
First of all, a good answer to "How to serve images using Node.js" is not implementing a static file server from scratch and doing it badly. A good answer is using a module like Express that does the job correctly.
Answering comments that say that using Express "doesn't explain much other than how to rely on someone else to get the job done" it should be noted, that using the http module already relies on someone else to get the job done. If someone doesn't want to rely on anyone to get the job done then at least raw TCP sockets should be used instead - which I do in one of my examples below.
A more serious problem is that all of the answers here that use the http module are broken. They introduce race conditions, insecure path resolution that will lead to path traversal vulnerability, blocking I/O that will completely fail to serve any concurrent requests at all and other subtle problems - they are completely broken as examples of what the question asks about, and yet they already use the abstraction that is provided by the http module instead of using TCP sockets so they don't even do everything from scratch as they claim.
If the question was "How to implement static file server from scratch, as a learning exercise" then by all means answers how to do that should be posted - but even then we should expect them to at least be correct. Also, it is not unreasonable to assume that someone who wants to serve an image might want to serve more images in the future so one could argue that writing a specific custom static file server that can serve only one single file with hard-coded path is somewhat shortsighted. It seems hard to imagine that anyone who searches for an answer on how to serve an image would be content with a solution that serves just a single image instead of a general solution to serve any image.
In short, the question is how to serve an image and an answer to that is to use an appropriate module to do that in a secure, performant and reliable way that is readable, maintainable and future-proof while using the best practice of professional Node development. But I agree that a great addition to such an answer would be showing a way to implement the same functionality manually but sadly every attempt to do that has failed so far. And that is why I wrote some new examples.
After this short introduction, here are my five examples doing the job on 5 different levels of abstraction.
Minimum functionality
Every example serves files from the public directory and supports the minimum functionality of:
MIME types for most common files
serves HTML, JS, CSS, plain text and images
serves index.html as a default directory index
responds with error codes for missing files
no path traversal vulnerabilities
no race conditions while reading files
I tested every version on Node versions 4, 5, 6 and 7.
express.static
This version uses the express.static built-in middleware of the express module.
This example has the most functionality and the least amount of code.
var path = require('path');
var express = require('express');
var app = express();
var dir = path.join(__dirname, 'public');
app.use(express.static(dir));
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
express
This version uses the express module but without the express.static middleware. Serving static files is implemented as a single route handler using streams.
This example has simple path traversal countermeasures and supports a limited set of most common MIME types.
var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');
var dir = path.join(__dirname, 'public');
var mime = {
html: 'text/html',
txt: 'text/plain',
css: 'text/css',
gif: 'image/gif',
jpg: 'image/jpeg',
png: 'image/png',
svg: 'image/svg+xml',
js: 'application/javascript'
};
app.get('*', function (req, res) {
var file = path.join(dir, req.path.replace(/\/$/, '/index.html'));
if (file.indexOf(dir + path.sep) !== 0) {
return res.status(403).end('Forbidden');
}
var type = mime[path.extname(file).slice(1)] || 'text/plain';
var s = fs.createReadStream(file);
s.on('open', function () {
res.set('Content-Type', type);
s.pipe(res);
});
s.on('error', function () {
res.set('Content-Type', 'text/plain');
res.status(404).end('Not found');
});
});
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
connect
This version uses the connect module which is a one level of abstraction lower than express.
This example has similar functionality to the express version but using slightly lower-lever APIs.
var path = require('path');
var connect = require('connect');
var app = connect();
var fs = require('fs');
var dir = path.join(__dirname, 'public');
var mime = {
html: 'text/html',
txt: 'text/plain',
css: 'text/css',
gif: 'image/gif',
jpg: 'image/jpeg',
png: 'image/png',
svg: 'image/svg+xml',
js: 'application/javascript'
};
app.use(function (req, res) {
var reqpath = req.url.toString().split('?')[0];
if (req.method !== 'GET') {
res.statusCode = 501;
res.setHeader('Content-Type', 'text/plain');
return res.end('Method not implemented');
}
var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
if (file.indexOf(dir + path.sep) !== 0) {
res.statusCode = 403;
res.setHeader('Content-Type', 'text/plain');
return res.end('Forbidden');
}
var type = mime[path.extname(file).slice(1)] || 'text/plain';
var s = fs.createReadStream(file);
s.on('open', function () {
res.setHeader('Content-Type', type);
s.pipe(res);
});
s.on('error', function () {
res.setHeader('Content-Type', 'text/plain');
res.statusCode = 404;
res.end('Not found');
});
});
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
http
This version uses the http module which is the lowest-level API for HTTP in Node.
This example has similar functionality to the connect version but using even more lower-level APIs.
var path = require('path');
var http = require('http');
var fs = require('fs');
var dir = path.join(__dirname, 'public');
var mime = {
html: 'text/html',
txt: 'text/plain',
css: 'text/css',
gif: 'image/gif',
jpg: 'image/jpeg',
png: 'image/png',
svg: 'image/svg+xml',
js: 'application/javascript'
};
var server = http.createServer(function (req, res) {
var reqpath = req.url.toString().split('?')[0];
if (req.method !== 'GET') {
res.statusCode = 501;
res.setHeader('Content-Type', 'text/plain');
return res.end('Method not implemented');
}
var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
if (file.indexOf(dir + path.sep) !== 0) {
res.statusCode = 403;
res.setHeader('Content-Type', 'text/plain');
return res.end('Forbidden');
}
var type = mime[path.extname(file).slice(1)] || 'text/plain';
var s = fs.createReadStream(file);
s.on('open', function () {
res.setHeader('Content-Type', type);
s.pipe(res);
});
s.on('error', function () {
res.setHeader('Content-Type', 'text/plain');
res.statusCode = 404;
res.end('Not found');
});
});
server.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
net
This version uses the net module which is the lowest-level API for TCP sockets in Node.
This example has some of the functionality of the http version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.
var path = require('path');
var net = require('net');
var fs = require('fs');
var dir = path.join(__dirname, 'public');
var mime = {
html: 'text/html',
txt: 'text/plain',
css: 'text/css',
gif: 'image/gif',
jpg: 'image/jpeg',
png: 'image/png',
svg: 'image/svg+xml',
js: 'application/javascript'
};
var server = net.createServer(function (con) {
var input = '';
con.on('data', function (data) {
input += data;
if (input.match(/\n\r?\n\r?/)) {
var line = input.split(/\n/)[0].split(' ');
var method = line[0], url = line[1], pro = line[2];
var reqpath = url.toString().split('?')[0];
if (method !== 'GET') {
var body = 'Method not implemented';
con.write('HTTP/1.1 501 Not Implemented\n');
con.write('Content-Type: text/plain\n');
con.write('Content-Length: '+body.length+'\n\n');
con.write(body);
con.destroy();
return;
}
var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
if (file.indexOf(dir + path.sep) !== 0) {
var body = 'Forbidden';
con.write('HTTP/1.1 403 Forbidden\n');
con.write('Content-Type: text/plain\n');
con.write('Content-Length: '+body.length+'\n\n');
con.write(body);
con.destroy();
return;
}
var type = mime[path.extname(file).slice(1)] || 'text/plain';
var s = fs.readFile(file, function (err, data) {
if (err) {
var body = 'Not Found';
con.write('HTTP/1.1 404 Not Found\n');
con.write('Content-Type: text/plain\n');
con.write('Content-Length: '+body.length+'\n\n');
con.write(body);
con.destroy();
} else {
con.write('HTTP/1.1 200 OK\n');
con.write('Content-Type: '+type+'\n');
con.write('Content-Length: '+data.byteLength+'\n\n');
con.write(data);
con.destroy();
}
});
}
});
});
server.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
Download examples
I posted all of the examples on GitHub with more explanation.
Examples with express.static, express, connect, http and net:
https://github.com/rsp/node-static-http-servers
Other project using only express.static:
https://github.com/rsp/node-express-static-example
Tests
Test results are available on Travis:
https://travis-ci.org/rsp/node-static-http-servers
Everything is tested on Node versions 4, 5, 6, and 7.
See also
Other related answers:
Failed to load resource from same directory when redirecting Javascript
onload js call not working with node
Sending whole folder content to client with express
Loading partials fails on the server JS
Node JS not serving the static image
I agree with the other posters that eventually, you should use a framework, such as Express.. but first you should also understand how to do something fundamental like this without a library, to really understand what the library abstracts away for you.. The steps are
Parse the incoming HTTP request, to see which path the user is asking for
Add a pathway in conditional statement for the server to respond to
If the image is requested, read the image file from the disk.
Serve the image content-type in a header
Serve the image contents in the body
The code would look something like this (not tested)
fs = require('fs');
http = require('http');
url = require('url');
http.createServer(function(req, res){
var request = url.parse(req.url, true);
var action = request.pathname;
if (action == '/logo.gif') {
var img = fs.readFileSync('./logo.gif');
res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(img, 'binary');
} else {
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end('Hello World \n');
}
}).listen(8080, '127.0.0.1');
You should use the express framework.
npm install express
and then
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
and then the URL localhost:8080/images/logo.gif should work.
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
res.writeHead(200,{'content-type':'image/jpg'});
fs.createReadStream('./image/demo.jpg').pipe(res);
}).listen(3000);
console.log('server running at 3000');
It is too late but helps someone, I'm using node version v7.9.0 and express version 4.15.0
if your directory structure is something like this:
your-project
uploads
package.json
server.js
server.js code:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/uploads'));// you can access image
//using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.
//Or you can change the directory for hiding real directory name:
`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg
app.listen(7000);
Vanilla node version as requested:
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
http.createServer(function(req, res) {
// parse url
var request = url.parse(req.url, true);
var action = request.pathname;
// disallow non get requests
if (req.method !== 'GET') {
res.writeHead(405, {'Content-Type': 'text/plain' });
res.end('405 Method Not Allowed');
return;
}
// routes
if (action === '/') {
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end('Hello World \n');
return;
}
// static (note not safe, use a module for anything serious)
var filePath = path.join(__dirname, action).split('%20').join(' ');
fs.exists(filePath, function (exists) {
if (!exists) {
// 404 missing files
res.writeHead(404, {'Content-Type': 'text/plain' });
res.end('404 Not Found');
return;
}
// set the content type
var ext = path.extname(action);
var contentType = 'text/plain';
if (ext === '.gif') {
contentType = 'image/gif'
}
res.writeHead(200, {'Content-Type': contentType });
// stream the file
fs.createReadStream(filePath, 'utf-8').pipe(res);
});
}).listen(8080, '127.0.0.1');
I like using Restify for REST services. In my case, I had created a REST service to serve up images and then if an image source returned 404/403, I wanted to return an alternative image. Here's what I came up with combining some of the stuff here:
function processRequest(req, res, next, url) {
var httpOptions = {
hostname: host,
path: url,
port: port,
method: 'GET'
};
var reqGet = http.request(httpOptions, function (response) {
var statusCode = response.statusCode;
// Many images come back as 404/403 so check explicitly
if (statusCode === 404 || statusCode === 403) {
// Send default image if error
var file = 'img/user.png';
fs.stat(file, function (err, stat) {
var img = fs.readFileSync(file);
res.contentType = 'image/png';
res.contentLength = stat.size;
res.end(img, 'binary');
});
} else {
var idx = 0;
var len = parseInt(response.header("Content-Length"));
var body = new Buffer(len);
response.setEncoding('binary');
response.on('data', function (chunk) {
body.write(chunk, idx, "binary");
idx += chunk.length;
});
response.on('end', function () {
res.contentType = 'image/jpg';
res.send(body);
});
}
});
reqGet.on('error', function (e) {
// Send default image if error
var file = 'img/user.png';
fs.stat(file, function (err, stat) {
var img = fs.readFileSync(file);
res.contentType = 'image/png';
res.contentLength = stat.size;
res.end(img, 'binary');
});
});
reqGet.end();
return next();
}
This may be a bit off-topic, since you are asking about static file serving via Node.js specifically (where fs.createReadStream('./image/demo.jpg').pipe(res) is actually a good idea), but in production you may want to have your Node app handle tasks, that cannot be tackled otherwise, and off-load static serving to e.g Nginx.
This means less coding inside your app, and better efficiency since reverse proxies are by design ideal for this.
This method works for me, it's not dynamic but straight to the point:
const fs = require('fs');
const express = require('express');
const app = express();
app.get( '/logo.gif', function( req, res ) {
fs.readFile( 'logo.gif', function( err, data ) {
if ( err ) {
console.log( err );
return;
}
res.write( data );
return res.end();
});
});
app.listen( 80 );
Let me just add to the answers above, that optimizing images, and serving responsive images helps page loading times dramatically since >90% of web traffic are images. You might want to pre-process images using JS / Node modules such as imagemin and related plug-ins, ideally during the build process with Grunt or Gulp.
Optimizing images means processing finding an ideal image type, and selecting optimal compression to achieve a balance between image quality and file size.
Serving responsive images translates into creating several sizes and formats of each image automatically and using srcset in your HTML allows you to serve optimal image set (that is, the ideal format and dimensions, thus optimal file size) for every single browser).
Image processing automation during the build process means incorporating it up once, and presenting optimized images further on, requiring minimum extra time.
Some great read on responsive images, minification in general, imagemin node module and using srcset.
//This method involves directly integrating HTML Code in the res.write
//first time posting to stack ...pls be kind
const express = require('express');
const app = express();
const https = require('https');
app.get("/",function(res,res){
res.write("<img src="+image url / src +">");
res.send();
});
app.listen(3000, function(req, res) {
console.log("the server is onnnn");
});
import http from "node:http";
import fs from "node:fs";
const app = http.createServer((req, res)=>{
if(req.url === "/" && req.method === "GET"){
res.writeHead(200, {
"Content-Type" : "image/jpg"
})
fs.readFile("sending.jpg", (err, data)=>{
if(err){
throw err;
}else{
res.write(data);
res.end();
}
})
}
}).listen(8080, ()=>{
console.log(8080)
})

Server is running on 8080, but browser says webpage is unavailable

I followed this tutorial (http://www.hongkiat.com/blog/node-js-server-side-javascript/) and when running the next to last script (for creating a static server) the command prompt says "Server running on port 8080", but when trying to access it at localhost:8080 I just get a webpage is unavailable error.
I have made an rule in the firewall to allow access to 8080 as well.
What could be causing this? Should i be trying to access the page from another address?
When I try to access the page i get the following error message in cmd:
C:\Users\id122302\Documents\test.js:11
path.exists(full_path,function(exists)
^
TypeError: undefined is not a function
at Server.<anonymous> (C:\Users\id122302\Documents\test.js:11:7)
at Server.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:491:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:343:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
This is my code:
var sys = require("sys");
my_http = require("http");
path = require("path");
url = require("url");
filesys = require("fs");
//Create Server
my_http.createServer(function(request,response)
{
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path,function(exists)
{
if (!exists)
{
response.writeHeader(404, {"Content-Type":"text/plain"});
response.write("404 Not Found\n");
response.end();
}
else
{
filesys.readFile(full_path, "binary", function(err,file)
{
if (err)
{
response.writeHeader(500,{"Content-Type":"text/plain"});
response.write(err + "\n");
response.end();
}
else
{
response.writeHeader(200);
response.write(file,"binary");
response.end();
}
});
}
});
}).listen(8080);
console.log("Server Running on 8080");
Your server shows an exception and a line number => go for that place !
As observed by #maniacnero, there's no more such thing as path.exists in the API. There's an fs.exists but it's been deprecated, to avoid abusive usage in node's concurrent context.
The feared scenario would be :
you check asynchronously if a file exists.
some other routine deletes/renames it in the meanwhile, or something else on the server does.
you think that the file exists so you try to open it and confidently don't handle the error case.
So the lessons learnt here are :
do things atomically
always deal with failures right away
Provided you stick to this discipline, there's no need for such thing as fs.exists. Here's a modified version of your code :
var sys = require("sys");
var http = require("http");
var path = require("path");
var url = require("url");
var fs = require("fs");
var port = 8080;
http.createServer(function(request,response) {
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
fs.readFile(full_path, function(err, file) {
if (err) {
response.writeHeader(404, {"Content-Type":"text/plain"});
response.write("404 Not Found\n");
response.end();
} else {
response.writeHeader(200);
response.write(file);
response.end();
}
});
}).listen(port);
console.log("Server Running on " + port);
I also removed those "binary" thingys, that are way outdated and not documented in the API either !
Playing around with sample code is a nice way to learn, but only if you don't do it blindly. ;) Especially in a weakly typed language building on a fast changing API and where myriads of tutorials have been written by utter beginners. This is your friend : https://nodejs.org/api/

Getting a binding error when trying to run Node http server

We are supposed to create a simple http node server that should respond to a root-url request with a file called index.html. Do not use ExpressJS. Code should have error checking and at least one callback. Put five or more html elements in your index.html. One of the elements should be a link to an external page.
This is the code I have:
var http = require("http");
var fs = require('fs');
var index = fs.readFileSync('index.html');
var server = http.createServer(function(request, response) {
fs.exists(index, function(exists) {
try {
if(exists) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<html>");
  response.write("<head>");
  response.write("<title>Hello World!</title>");
  response.write("</head>");
  response.write("<body>");
response.write("<div>");
  response.write("Hello World!");
response.write("</div>");
response.write("<a href='http://www.google.com' target='_blank'>Google</a>")
  response.write("</body>");
  response.write("</html>");
} else {
response.writeHead(500);
}
} finally {
response.end(index);
}
});
});
 
server.listen(80);
console.log("Server is listening");
And I am getting this binding error:
Server is listening
fs.js:166
binding.stat(pathModule._makeLong(path), cb);
^
TypeError: path must be a string
at Object.fs.exists (fs.js:166:11)
at Server.<anonymous> (/Users/rahulsharma/Desktop/server.js:8:4)
at Server.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2112:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1970:22)
at TCP.onread (net.js:527:27)
Any thoughts?
Replacing the index variable with 'index.html' will do the job but
please Do NOT use fs.exists , read its API doc
http://nodejs.org/api/fs.html#fs_fs_exists_path_callback
Place the index.html with the .js file. Put all the html in that file.
var http = require("http");
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile("index.html",function(err,content){
if(err){
throw err;
console.log("Error reading index file.");
res.send("Aw snap!");
}
else{
res.writeHead(200,{"Content-type":"text/HTML"});
res.end(content,"UTF-8");
}
});
});
server.listen(80);
According to you stack trace the error is inside this line:
fs.exists(index, function(exists)
What you pass to this function(which checks if given file exists) is actually content of the file. What you should pass as first argument is probably "index.html" instead of index variable
You are trying to call fs.exists which expects a string path and you are giving it a filehandler index.
That's why the error is:
path must be a string
Either try using the string "index.html" and do not read it sync there. Do it async in the exists callback
fs.exists("index.htm", function(){ fs.readFile("index.htm")

Formidable multi-file upload - ENOENT, no such file or directory

I know this question has been asked but my mind has been blown by my inability to get this working. I am trying to upload multiple images to my server with the following code:
var formidable = require('formidable');
var fs = require('fs');
...
router.post('/add_images/:showcase_id', function(req, res){
if(!admin(req, res)) return;
var form = new formidable.IncomingForm(),
files = [];
form.uploadDir = global.__project_dirname+"/tmp";
form.on('file', function(field, file) {
console.log(file);
file.image_id = global.s4()+global.s4();
file.endPath = "/img/"+file.image_id+"."+file.type.replace("image/","");
files.push({field:field, file:file});
});
form.on('end', function() {
console.log('done');
console.log(files);
db.get("SOME SQL", function(err, image_number){
if(err){
console.log(err);
}
var db_index = 0;
if(image_number) db_index = image_number.image_order;
files.forEach(function(file, index){
try{
//this line opens the image in my computer (testing)
require("sys").exec("display " + file.file.path);
console.log(file.file.path);
fs.renameSync(file.file.path, file.file.endPath);
}catch (e){
console.log(e);
}
db.run( "SOME MORE SQL"')", function(err){
if(index == files.length)
res.redirect("/admin/gallery"+req.params.showcase_id);
});
});
});
});
form.parse(req);
});
The line that opens the image via system calls works just fine, however I continue to get:
Error: ENOENT, no such file or directory '/home/[username]/[project name]/tmp/285ef5276581cb3b8ea950a043c6ed51'
by the rename statement.
the value of file.file.path is:
/home/[username]/[project name]/tmp/285ef5276581cb3b8ea950a043c6ed51
I am so confused and have tried everything. What am I doing wrong?
Probably you get this error because the target path does not exist or you don't have write permissions.
The error you get is misleading due to a bug in nodejs, see:
https://github.com/joyent/node/issues/5287
https://github.com/joyent/node/issues/685
Consider adding:
console.log(file.file.endPath);
before the fs.renameSync call and check if the target path exist and is writable by your application
You stated form. Therefore note that Formidable doesn't work out of the box with just NodeJS. Unless you were to use something like the prompt module for input. If you are using HTML, you'll need something like Angular, React or Browserify to be able to give it access to your interface.

Resizing image error with gm package of node js

I've been trying this for a while, but I keep getting the error:
Error: Command failed: Invalid Parameter - /images
I installed ImageMagick and the gm package, so that's definitely not the problem.
gm(imageLocation)
.resize(100) // use your own width and height
.write('here.jpg', function (err) {
if (!err) console.log(' hooray! ');
else console.log(err);
});
imageLocation being ./images/3.jpg. Why does this error keep happening? I looked at the documentation
I'm on a Windows 32 bit machine. My server is supposed to get an image from a folder, resize it, and then display it. It seems like I have to write the resized photo and then display that, but the writing process always errors out and the image ends up being empty.
If there's a way to skip the writing part and just displaying the photo directly, that would be awesome too.
Thanks!
URL Query I used: http://localhost:8123/images/3.jpg
Complete code:
var querystring = require('querystring'); //used for parsing parts of urls
url = require('url');
http = require('http');
fs = require('fs');
gm = require('gm').subClass({ imageMagick: true });;
var server = http.createServer();
server.on('request', function(request, response){
var parsed_url = url.parse(request.url, true); //true gets the query as well
imageLocation = '.' + parsed_url.pathname;
gm(imageLocation)
.resize(100) // use your own width and height
.write('here.jpg', function (err) {
if (!err) console.log(' hooray! ');
else console.log(err);
});
if (getImage('here.jpg', response)){
//image is displayed
}
else{
respond404(parsed_url.pathname, response);
}
})
function respond404(path, response){
respond(404, "The requested path " + path + " was not found", response)
}
function getImage(location, response)
{
try{
var img = fs.readFileSync(location);
response.writeHead(200, {'Content-Type':'image/jpg'}); //parse this end
response.end(img, 'binary');
return true;
}catch(e){
return false;
}
}
server.listen(8123);
The answer Svbaker put can be used in Linux (maybe Mac as well?)
For Windows I got it to work by opening the command line in administrator mode and starting my server there.
I was able to get your code to work by changing how you required gm as follows:
var gm = require('gm');
I also had to remember to execute node with the correct permissions in my case:
sudo node server.js

Categories

Resources