fs.createwritestream is not a function - node.js

I am Trying to develop a react app that help me to download files to my amazon cloud.
For that i used This module
download-file-with-progressbar
Here is my code:
var dl = require('download-file-with-progressbar');
//-----------Download File-------------------
option = {
filename: 'fileName',
dir: os.tmpdir(),
onDone: (info)=>{
console.log('done', info);
},
onError: (err) => {
console.log('error', err);
},
onProgress: (curr, total) => {
console.log('progress', (curr / total * 100).toFixed(2) + '%');
},
}
dd = dl('https://nodejs.org/dist/v6.10.2/node-v6.10.2-linux-x64.tar.gz', this.option);
//-------------------------------------------
It is working fine on nodejs project. But when i used it in a react project(created using 'create-react-app') it produced following error.
TypeError: fs.createWriteStream is not a function
My idea of the project is to create a react app that help to download files to my server or cloud space. how to fix that error.

The createWriteStream is a function part of the Nodejs API, that is why it is working fine when you run it as a nodejs project.
But when you run a React app, it is your browser that executes your code and not nodejs. And browsers don't know about this API.
If you want to download a file from a React application, you have to do it through an HTTP request. You can use the fetch API for example.

Related

Getting TypeError: t.filter is not a function when application is deployed in heroku

I have developed a web application using VueJS 2 , sequelize 5.22, Vuetify 2.4, Postgres , NodeJS 15.12 and ExpressJS 4.16 . the application works fine and tested completely in local machine and running without any error and issue.
After deploying in Heroku, although the application is running and showing all pages, and connected to Postgres database, However data is not coming up in v-data-table on pages and there are below error
TypeError: t.filter is not a function
Error
on Server side , this is controller for getting list of data:
async index(req, res) {
try {
const currency = await Currency.findAll();
res.send(currency)
} catch (err) {
res.status(400).send({
error: 'Error in showing list of currencies ...'
})
}
},
and in client side , using this code :
async mounted() {
this.currencies = (await CurrencyService.index()).data;
},
Please let me know how I could fix this issue

Upload image from React Native to Apollo Server not working?

I have created my backend with Nodejs and Apollo Server. I am trying to upload an image from my React Native client. Here is my backend code
Mutation: {
async singleUpload(_, { fileInput: { file, fileName } }) {
try {
const { createReadStream, filename, mimetype } = await file;
const stream = createReadStream();
const path = `./upload/${filename}`;
const tempFile = { id: 123, filename, mimetype, path };
await new Promise((resolve, reject) => {
const writeStream = createWriteStream(path);
// When the upload is fully written, resolve the promise.
writeStream.on("finish", resolve);
// If there's an error writing the file, remove the partially written file
// and reject the promise.
writeStream.on("error", (error) => {
unlink(path, () => {
reject(error);
});
});
// In node <= 13, errors are not automatically propagated between piped
// streams. If there is an error receiving the upload, destroy the write
// stream with the corresponding error.
stream.on("error", (error) => writeStream.destroy(error));
// Pipe the upload into the write stream.
stream.pipe(writeStream);
});
...then upload it to Firebase Storage
When I use Altair plugin for Firefox browser to upload image , it works fine.
Now for my React Native client, I am using apollo-upload-client lib. After a user picks image using the Image Picker plugin for React Native , I am creating a file
const file = new ReactNativeFile({
uri: image.uri,
type: image.type,
name: 'Hi there',
});
ReactNativeFile is from apollo-upload-client lib. Now when I upload it I get an error saying from my backend saying TypeError: createReadStream is not a function which I understand as there is no createReadStream parameter in my ReactNativeFile
so I decided to change my backend code to something like this
const { name, type } = await file;
console.log("Mime" + type);
const stream = fs.createReadStream(name);
fs module is from nodejs
Now when I try uploading image from Altair or from React Native , I get an error saying
[Error: ENOENT: no such file or directory,
Due to my lack of knowledge of backend I am not sure what is causing the issue.
I think if I try uploading it from ReactJS instead of React Native, my code might work for the backend.
But the image picker for browser and native mobile are very much different and I have not tried doing with ReactJS for now
I am following this article https://moonhighway.com/how-the-upload-scalar-works for my backend code

Sending a PDF from client to server isn't working with stream.pipe(res) in Ubuntu server

I have an application that makes a PDF and sends it to the client using node js. The application works perfectly locally but when I host it in a Ubuntu server in Digital Ocean, the endpoint that generates the PDF isn't working
This is the code that sends the PDF to the client :
pdf.create(html, options).toStream((err, stream)=> {
if (err) {
res.json({
message: 'Sorry, we were unable to generate pdf',
});
}
stream.pipe(res)
});
in the client side this how i communicate with the endpoint
genratePdf({ commit }, data) {
axios.post('http://localhost:1337/getpdf', data,{ responseType:'arraybuffer' }).then((response) => {
let blob = new Blob([response.data],{type:'application/pdf'})
var link=document.createElement('a');
link.href=URL.createObjectURL(blob);
link.download="Report_"+new Date()+".pdf";
link.click();
}, (err) => {
console.log(err)
})
When i run it locally it works perfectly:
but when I host in a Ubuntu Digital Ocean droplet the other endpoint work but the generated PDF one is not working and it shows me that error
I think it's a timeout problem the app does not wait for the stream to finish to pipe it in res.
There is actually an error occuring in the generation of your pdf but because you are not returning when handling error, it still executes the stream.pipe statement.
Change your code to this :
pdf.create(html, options).toStream((err, stream)=> {
if (err) {
console.error(err);
return res.json({
message: 'Sorry, we were unable to generate pdf',
});
}
return stream.pipe(res)
});
Notice I added a console.error(err);, it might help you to debug further. But I think the library you are using uses PhantomJS, might be an error with it as PhantomJS must be compiled for the arch.
Try doing rm -Rf ./node_modules && npm i

Show BASE64 video with node/express

So, bit of an odd problem. I have a bunch of media files saved as base64 strings in mongo, some are images, some are videos.
I made an API for getting the media files:
app.get('/api/media/:media_id', function (req, res) {
media.findById(req.params.media_id)
.exec(function (err, media) {
if (err) {
res.send(err);
}
var file = new Buffer(media.file, 'base64');
res.writeHead(200, {'Content-Type': media.type, 'Content-Transfer-Encoding': 'BASE64', 'Content-Length': file.length});
res.end(file);
});
});
Now, images have no problems. They load just fine, both directly from the API, and when I call the API from a front-end (for example <img src="/api/media/23498423">)
THE PROBLEM
If I fetch a video from a front-end, like the images - but with a video- or object-tag:
<video src="/api/media/3424525" controls></video>
there's no problem, but if I load the video in a browser directly from the API:
http://localhost:8080/api/media/3424525
the server process crashes, no errors. It simply just freezes up. And we're not talking about huge video files - it's a 1.5MB video.
The media type in the header for all the videos I'm testing with is video/mp4. Oh, and just to be clear: if I do the same with images, everything works perfectly.
EDIT:
Okay, so as suggested by #idbehold and #zeeshan I took a look at gridfs and gridfs-stream, and for the purpose of my app, this certainly is what I should have used in the first place. However, after implementing gridfs in my app, the problem still persists.
app.get('/api/media/:media_id', function (req, res) {
gfs.findOne({ _id: req.params.media_id }, function (err, file) {
if (err) {
return res.status(400).send(err);
}
if (!file) {
return res.status(404).send('');
}
res.set('Content-Type', file.contentType);
res.set('Content-Disposition', 'inline; filename="' + file.filename + '"');
var readstream = gfs.createReadStream({
_id: file._id
});
readstream.on("error", function (err) {
console.log("Got an error while processing stream: ", err.message);
res.end();
});
readstream.pipe(res);
});
});
When I call the media file (be it image or video) from a front-end, within a HTML tag, everything works out fine. But if I load a video (again, smallish videos from 1.5mb to max 6mb total size) directly in the browser, the server process freezes. To be a bit more clear: I am testing on windows, and the server app (server.js) is run in console. The console and the process it is running is what freezes. I cannot load any more pages/views in the node app, and I cannot even stop/kill/shutdown the node app or the console.
Streaming videos directly to/from GridFS using gridfs-stream either with mongodb-native db instance or mongoose.
var mongo = require('mongodb'),
Grid = require('gridfs-stream'),
db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017)),
gfs = Grid(db, mongo);
//store
app.post('/video', function (req, res) {
req.pipe(gfs.createWriteStream({
filename: 'file_name_here'
}));
res.send("Success!");
});
//get
app.get('/video/:vid', function (req, res) {
gfs.createReadStream({
_id: req.params.vid // or provide filename: 'file_name_here'
}).pipe(res);
});
for complete files and running project:
Clone node-cheat direct_upload_gridfs, run node app followed by npm install express mongodb gridfs-stream.
Truly an odd problem...
I could be way off, but it's worth a shot:
One of the differences when opening a url directly from the browser is that the browser will also try to fetch http://localhost:8080/favicon.ico (while trying to find the tab icon). Maybe the problem is not related to your video code, but rather to some other route, trying to handle the /favicon.ico request?
Have you tried using wget or curl?
I don't know the answer, maybe this is a dumb suggestion, but what is the browser you are using? Maybe something from Microsoft causes the problem...

PhoneGap Facebook Connect Plugin - simple walkthrough?

For the past two days, I have been trying to figure out how to make use of the phonegap-facebook-plugin
What I did so far:
I created a new phonegap app (phonegap create app --id
"com.example.test" --name"app")
I cloned the repo and saved it into the app so now my app has a
plugin folder that contains the phonegap-facebook-plugin with two
platform examples in it (ios and adnroid).
I downloaded the phonegap ios app from the app store, started
phonegap serve inside the my sample app's www folder (the top www
folder - the one you're supposed to be working on), and I can see it
running on my phone.
I added the following code to the app's index.js:
onDeviceReady: function() {
app.receivedEvent('deviceready');
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
}
facebookConnectPlugin.login(["public_profile"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
},
I added this to my index.html:
<div class="event listening button" onclick="login();">Login with Facebook</div>
When I serve with phonegap, and open on my iphone with the phonegap app, I can see the button LOGIN WITH FACEBOOK. Clicking it doesn't do anything.
Could someone PLEASE create a SIMPLE walkthrough for the installation of this plugin?
Remove this Code :
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
}
facebookConnectPlugin.login(["public_profile"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
Added code in bottom of index.js
function login(){
facebookConnectPlugin.login( ["public_profile","email"],function (response) {
if(response.authResponse.userID!=''){
facebookConnectPlugin.api(response.authResponse.userID+"/?fields=id,email,first_name", ["public_profile"],
function (response) {
console.log(response);
},
function (response) {
console.log(response);
});
}
},
function (response) {
console.log(response);
});
}
And it will work. Let me know if its not working. Ty
example

Resources