How to download file from server using nodejs - express

I want to download file from other website to my pc using expressjs
I tried to use: res.download to download but it seems to be worked on my own server only
Here is my code:
res.download('http://apkleecher.com/download/dl.php?dl=com.instagram.android', 'folder', function(err){
if (err) {
console.log(err);
} else {
}
});
And it return the error:
{ Error: ENOENT: no such file or directory, stat '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android'
errno: -2,
code: 'ENOENT',
syscall: 'stat',
path: '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android',
expose: false,
statusCode: 404,
status: 404 }
In my guess, the problem is in the path of url.

Turning my comment into an answer since it worked for you...
You can fetch a resource from a remote web server using either http.get() or the request() module in node. If you like to use promises for your asynchronous operations, then the request-promise module is a promisified version of the request module and works great.
You can also use just plain http.get(), but it's a lot more work because you have to read the stream, rather the results yourself and install appropriate error handling, all of which the request() module does for you in one simple call.
Here's a simple example using the request-promise module:
const rp = require('request-promise');
rp('http://www.google.com').then(function (htmlString) {
// Process html...
}).catch(function (err) {
// process error here
});

res.download requires a path to your local filesystem.
try this:
res.redirect("http://apkleecher.com/download/dl.php?dl=com.instagram.android")

best way to download remote file is use stream .its use small mount of memory
**npm i got**
//========================
const got=require('got');
const fs=require('fs');
const path=require('path');
file_downloader(link,file_name){
var file_path = path.join(__dirname,file_name);
await got.stream(encodeURI(link))
.on('response', async (data) => {
//first response check headers like ['content-length']
})
.on('error', async (error) => {
console.log("===========Stream Error======= ");
console.log(error);
console.log("===========//End Stream Error======= ");
})
.on('downloadProgress', async (progress) => {
console.log(file.name, progress);
})
.pipe(fs.createWriteStream(file_path));
}

Related

Sveltekit: Can't call API from +layout.ts. Error: "Failed to parse URL from /api/..."

This is the code in my +layout.ts
import type { LayoutLoad } from './$types';
export const load: LayoutLoad = async () => {
const response = await fetch('/api/thumbnails', { method: 'GET' })
if (response.ok) {
return { json: await response.json() }
}
else {
console.log('There were no blog posts to get.')
// TODO: do something!
}
};
I had the exact same code in a +page.ts file (the only difference was LayoutLoad was changed to PageLoad), and it worked there. I was calling my thumbnails api and populating my page. I don't understand why it doesn't work at all in +layout. It just crashes my web app.
On top of this, LayoutLoad has an error in VsCode that reads Module '"./$types"' has no exported member 'LayoutLoad'. I don't understand why this is. Can somebody help me?
I figured it out, the answer was here: https://kit.svelte.dev/docs/load#making-fetch-requests
To get data from an external API or a +server.js handler, you can use the provided fetch function, which behaves identically to the native fetch web API with a few additional features:
Basically, in my code I had to change this line
export const load: LayoutLoad = async () => {
to this
export const load: LayoutLoad = async ({fetch}) => {
Because without that change I was using the native fetch and not sveltekit's provided fetch.
Also, I seemed to have fixed this error: Module '"./$types"' has no exported member 'LayoutLoad' by updating sveltkit to the latest version.

Jira rest apis - not understanding which url to use

i want to basic authentication using nodejs in documentation. it is written that use "localhost:8080". i am not understanding which url to use. in some other documentation, it is said it deprecated. to make request i am using axios npm package
some things that i tried but didn't work.
- axios.get("https://example.atlassian.net",{data:{username:"",password:""}}).then((result) => {})
please help me guys? i stucked in this problem from last 2 days. Thanks in advance
I think this will help you
Install with the node package manager npm:
$ npm install jira-client
// With ES5
var JiraApi = require('jira-client');
// With ES6
import JiraApi from 'jira-client';
// Initialize
var jira = new JiraApi({
protocol: 'https',
host: 'jira.somehost.com',
username: 'username',
password: 'password',
apiVersion: '2',
strictSSL: true
});
Example: Find the status of an issue
// ES5
// We are using an ES5 Polyfill for Promise support. Please note that if you don't explicitly
// apply a catch exceptions will get swallowed. Read up on ES6 Promises for further details.
jira.findIssue(issueNumber)
.then(function(issue) {
console.log('Status: ' + issue.fields.status.name);
})
.catch(function(err) {
console.error(err);
});
// ES6
jira.findIssue(issueNumber)
.then(issue => {
console.log(`Status: ${issue.fields.status.name}`);
})
.catch(err => {
console.error(err);
});
// ES7
async function logIssueName() {
try {
const issue = await jira.findIssue(issueNumber);
console.log(`Status: ${issue.fields.status.name}`);
} catch (err) {
console.error(err);
}
}
Documentation
documentation here

Axios throws self signed certificate error in asyncData (nuxt)

I am working on a project and I am using nuxt for it. API calls are being made to node.js server over https, and since everything is in my local development, I am using self signed certificates.
When I try to make axios call from asyncData, I receive
ERROR self signed certificate 15:08:11
at TLSSocket.onConnectSecure (_tls_wrap.js:1049:34)
at TLSSocket.emit (events.js:182:13)
at TLSSocket.EventEmitter.emit (domain.js:442:20)
at TLSSocket._finishInit (_tls_wrap.js:631:8)
Same error shows when i try to make axios call from nuxtServerInit .
Identical call made from methods and called with #click gets the data and works. Also, other calls in store actions also work without issues.
Is there a reason why this calls don't work, and also, is there a way to make axios calls as described above?
this doesn't work:
async asyncData(context) {
let result = await context.app.$axios.$get("/item", {
headers: {
"x-auth": context.store.getters["login/getToken"]
}
});
console.log("item: ", result.item);
}
and this does work without problems:
methods: {
async getItem() {
try {
let result = await this.$axios.$get("/item", {
headers: {
"x-auth": this.$store.getters["login/getToken"]
}
});
console.log("item : ", result.item);
} catch (e) {
console.log(e);
}
}
}
Thank you for help

Preload / Pre-populate PouchDB in React Native Application

Is it possible to preload / pre-populate a database in my React Native application and then the first time it is run, simply do a sync? I already have most, if not all of the database information before the app is distributed, it would be awesome if it just had to do a quick sync when the app is run. Any ideas how I would go about doing that?
I found this - https://pouchdb.com/2016/04/28/prebuilt-databases-with-pouchdb.html but it doesn't mention React Native
Using:
pouchdb-find: ^7.0.0
pouchdb-react-native: ^6.4.1
react: 16.3.1
react-moment: ^0.7.9
react-native: ~0.55.2
Thanks for any pointers.
Update Here is the code I'm using to try the loading of a dump file. This code exists in /screens/Home.js
The dump file is located in /client/dbfile/database.txt
var db = new PouchDB("cs1");
db.get("_local/initial_load_complete")
.catch(function(err) {
console.log("loading dumpfile");
if (err.status !== 404) {
// 404 means not found
throw err;
}
db.load("/client/dbfile/database.txt").then(function() {
return db.put({ _id: "_local/initial_load_complete" });
});
})
.then(function() {
// at this point, we are sure that
// initial replication is complete
console.log("loading is complete!");
return db.allDocs({ include_docs: true });
})
.then(
function(res) {
// display all docs for debugging purposes (empty)
console.log(res);
});
this.localDB = db;
When this runs my console displays this - showing there have been 0 rows added.
Object {
"offset": 0,
"rows": Array [],
"total_rows": 0,
}
Possible Unhandled Promise Rejection (id: 0):
Object {
"message": undefined,
"name": "unknown",
"status": 0,
}
In my project I have couple of db docs I distribute with app (translations JSON is the one good example).
So at app init I just try to read translations doc from db, if there is none - I import content from js module and store in db.
Then translations changes just being replicated from server to local db.
//transmob.js
const transMobFile = {
//content goes here
);
module.exports = transMobFile
//dbInit.js
import transMobFile from 'data/transMob';
..
PDB.getDoc('TransMob')
.then((doc)=> {
if (!doc) {
global.locales = transMobFile.localesMob; // locales
global.translations = transMobFile.langMob; // translations
return PDB.saveDoc('TransMob', transMobFile)
}
})
You can use react-native-fs to load a file from /android/app/src/main/assets. Just put the file into the assets folder and read it with RNFS.readFileAssets.
import PouchDB from 'pouchdb-core';
PouchDB
.plugin(require('pouchdb-find'))
.plugin(require('pouchdb-load'));
import RNFS from 'react-native-fs';
const localDB = new PouchDB("cs1", {adapter: 'asyncstorage'});
localDB.get("_local/initial_load_complete")
.catch(function(err) {
console.log("loading dumpfile");
if (err.status !== 404) {
// 404 means not found
throw err;
}
RNFS.readFileAssets('yourdb.txt', 'utf8')
.then((contents) => {
localDB.load(contents).then(function() {
return localDB.put({ _id: "_local/initial_load_complete" });
}).then(function() {
// at this point, we are sure that
// initial replication is complete
console.log("loading is complete!");
return localDB.allDocs({ include_docs: true }).then(
function(res) {
// display all docs for debugging purposes (empty)
console.log(res);
});
}, function(err) {
console.log(err);
});
})
})
You'll need to rebuild your project, reloading is not sufficient.
My project crashes when I attempt to load a 30MB file, so I probably will split it into a few smaller files. Check out https://github.com/pouchdb-community/pouchdb-load to see how this works if needed.
I found that the db.load() function from the pouchdb-load module requires a URL. I was pointing it to a file path on the device's filesystem. I placed my database.txt file on my server, changed it to use the url and it worked.
In my mind this isn't ideal because if they install the app and have slow wireless, it still has to pull the file from the server. It is still much faster than performing a full-on replicate when the app opens for the first time however.

Asynchronous controller in Express for Form parsing to Mongoose

Currently, I'm developing a way to upload a message (file and fields) from Dropzone to Mongoose using Express Router. My back-end controller (which is called after authentication and data validation) goes as follows:
//Import Internal Dependencies
const Loader = require('../models/loader.js');
const Formidable = require('formidable');
const fs = require('fs');
module.exports = {
load: async (req, res, next) => {
var form = new Formidable.IncomingForm();
let path;
let contentType;
await form.parse(req, async function (err, fields, files) {
if (err) {
return res.status(404).json(err);
} else {
const {
user,
patient,
condition,
compound,
classi
} = fields;
path = files.image.path;
contentType = files.image.type;
fs.readFile(path, async function (err, data) {
if (err) {
return res.status(404).json(err);
} else {
//Save load
const newLoader = new Loader({
user,
patient,
condition,
compound,
classi,
image: {
data,
contentType
}
});
//Delete image in local storage
await fs.unlink(path, function (error) {
if(error){
return res.status(404).json(error)
}
});
await newLoader.save();
res.status(200).json("Load image sucessfully.");
next()
}
})
}
});
}
};
When I test it with Postman I got a status 202 and images are successfully upload to the database. However, when I try to upload with dropzone without the fields (which should cause some error and be displayed in dropzone) I got the following errors/warning in the back-end console (Dropzone stoped at upload and didn't show any error):
(node:20834) UnhandledPromiseRejectionWarning: ValidationError: load validation failed: user: Path `user` is required., classi: Path `classi` is required.
at new ValidationError (/root/aimuneBack/node_modules/mongoose/lib/error/validation.js:27:11)
at model.Document.invalidate (/root/aimuneBack/node_modules/mongoose/lib/document.js:1876:32)
at p.doValidate.skipSchemaValidators (/root/aimuneBack/node_modules/mongoose/lib/document.js:1744:17)
at /root/aimuneBack/node_modules/mongoose/lib/schematype.js:808:9
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:20834) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20834) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
at emitWarning (internal/process/promises.js:92:15)
at emitPendingUnhandledRejections (internal/process/promises.js:109:11)
at process._tickCallback (internal/process/next_tick.js:189:7)
POST /load - - ms - -
So I know I have done something wrong with my asynchronous code and unfortunately cannot figure it out. Hope you can help. Best regards, Andre