Is it possible to create a rest api responsing an image file using node? Wondering if there is a proper way to do this.
I have studying fs module to find something.
you can do it
var fs = require('fs'),
fs.readFile(__dirname + req.url, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
For more details see here
Related
I need to write a file on a remote server folder, i'm using fs on nodejs. This is my code, the function return with no errors but it doesn´t write the file on the folder.
fs.writeFile('https:/someurl.com/Content/myfiles/message.txt', 'Hello Node.js', 'utf8', (err) => {
console.log(err)
})
You cannot use fs to access remote file systems, you have to relay on third party libraries.
Upload:
You can use a third party library like ftp to upload to a public ftp:
var Client = require('ftp');
var fs = require('fs');
var c = new Client({ host: 'someurl.com', port: 21});
c.on('ready', function() {
c.cwd('/Content/myfiles', function(err) {
if(!err) {
c.put('/local/path/message.txt', 'message.txt', function(err) {
if (err) throw err;
c.end();
});
}
});
});
c.connect();
Assuming you have access to that server, ftp also provides support for servers that require simple authentication.
Download:
You can use request library to fetch the file, then use fs to write it to your file system:
var request = require('request');
request.get('https:/someurl.com/Content/myfiles/message.txt', function (error, response, body) {
if (!error && response.statusCode == 200) {
fs.writeFile('message.txt', body, 'utf8', (err) => {
console.log(err)
})
}
});
You can't do it. fs is only for the filesystem where the code is being executed.
The only way is that the server you are pointing to should have an API at which, by passing certain parameters, write the file in that path.
node js resize and save image from remote server.
Hi,
How can I resize image without to save locally and then to save it.
when I run bellow code, I get error: "Error: Input buffer contains unsupported image format"
code:
var fs = require('fs');
var request = require('request');
var sharp = require('sharp');
function getImage()
{
request('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', function (err, res, body) {
var binary = Buffer.from(body.toString(), 'base64');
sharp(binary).resize(198, 110).toFile('test.jpg', (err, info ) =>
{
console.log('err: ', err);
console.log('info: ', info);
});
});
}
I found resolving for my question:
var resizer = sharp().resize(198, 110).toFile('test.jpg', (err, info) => {
console.log('err: ', err);
console.log('info: ', info);
});
request('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png').pipe(resizer);
If you can make sure that https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png returns the image, you can try to pipe the response directly to sharp rather than converting response to base64 format & processing.
var resize = sharp(binary).resize(198, 110);
resize.on('error', function() {
//handle error
});
resize.on('finish', function() {
// done
});
request('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png')
.pipe(process);
Update:
Removed .toFile('test.jpg'); part
I'm trying to generate a PDF from an HTML file from the frontend and the users may download the PDF (never be stored on the server).
For this I am using the module: html5-to-pdf
My code is like this:
var pdf = require('html5-to-pdf');
var fs = require('fs');
router.post('/pdf', function(req, res) {
var html = req.body.html;
if (!html) {
return res.sendStatus(400);
}
pdf().from.string(html).to.buffer({
renderDelay: 1000
}, function(err, data) {
if (err) {
return res.sendStatus(500);
}
var file = fs.createWriteStream('myDocument.pdf');
file.write(data, function(err) {
if (err) {
res.sendStatus(500);
}
res.download('myDocument');
});
});
});
Whenever I download a file size of 0Bytes and also creates the file on the server
Someone could help me?
Maybe it send file before write finish
file.on('end',function(){
res.download('myDocument');
})
The problem is that html5-to-pdf used phantom to generate the PDF, so it phantom deploys a little server at "localhost" and the port 0, the fact is that OpenShift not recognize "localhost"[1] and if instead of using "localhost" variable is used: process.env.OPENSHIFT_NODEJS_IP the application works correctly.
[1] https://github.com/amir20/phantomjs-node/tree/v1#use-it-in-restricted-enviroments
My goal is to accept an uploaded file and stream it to Wistia using the the Wistia Upload API. I need to be able to add fields to the HTTP request, and I don't want the file to touch the disk. I'm using Node, Express, Request, and Busboy.
The code below has two console.log statements. The first returns [Error: not implemented] and the second returns [Error: form-data: not implemented]. I'm new to streaming in Node, so I'm probably doing something fundamentally wrong. Any help would be much appreciated.
app.use("/upload", function(req, res, next) {
var writeStream = new stream.Writable();
writeStream.on("error", function(error) {
console.log(error);
});
var busboy = new Busboy({headers: req.headers});
busboy.on("file", function(fieldname, file, filename, encoding, mimetype) {
file.on("data", function(data) {
writeStream.write(data);
});
file.on("end", function() {
request.post({
url: "https://upload.wistia.com",
formData: {
api_password: "abc123",
file: new stream.Readable(writeStream)
}
}, function(error, response, body) {
console.log(error);
});
});
});
req.pipe(busboy);
});
I am not to familiar with the busboy module, but there errors you are getting are from attempting to use un-implemented streams. Whenever you create a new readable or writable stream directly from the stream module you have to create the _read and _write methods respectively Stream Implementors (node.js api). To give you something to work with the following example is using multer for handling multipart requests, I think you'll find multer is easier to use than busboy.
var app = require('express')();
var fs = require('fs');
var request = require('request');
app.use(multer());
app.post("/upload", function(req, res, next) {
// create a read stream
var readable = fs.createReadStream(req.files.myfile.path);
request.post({
url: "https://upload.wistia.com",
formData: {
api_password: "abc123",
file: readable
}
}, function(err, res, body) {
// send something to client
})
});
I hope this helps unfortunately I am not familiar with busboy, but this should work with multer, and as I said before there problem is just that you are using un-implemented streams I'm sure there is a way to configure this operation with busboy if you wanted.
If you want to use multipart (another npm) here is a tutorial:
http://qnimate.com/stream-file-uploads-to-storage-server-in-node-js/
I have just started with node.js. I find the asynchronous coding style it uses to be very impressive indeed. However, for those of us who are used to Java and Python it does take some time to get used to it.
I know the following code works fine. This is verified by several questions on this forum. I have also tried it on my own.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
http.createServer(function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.write("Other things");
response.end();
}).listen(3000);
});
The way I am interpretting this is as follows:
1. Try reading the html file
i. When done create a server
ii. Send it over to the client
2. Do everything else.
However, we can also have a chain of thoughts as follows:
1. Create the server
2. Try reading the file
i. When done. Send it over to the client
3. In the meanwhile do anything else the server might be asked to do.
The code corresponding to the second chain of thoughts is:
var http = require('http'),
fs = require('fs');
http.createServer(function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
response.write(html);
response.write("Other things");
});
response.end();
}).listen(3000);
While the first code works as expected. The second one displays nothing at all in the browser.
Why is the second chain of thoughts wrong?
Actually, what happens here is that the following function gets called each time there is an incoming request:
function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.write("Other things");
response.end();
}
You replaced that with:
function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
response.write(html);
response.write("Other things");
});
response.end();
}
Now here, it will run the following:
Write the header
Queue the readFile
Immediately execute the following: response.end();
By the time it is done reading the file and wants to write the contents, you already ended the response