Access locally stored file in NodeJS/Express - javascript

I am looking to access the locally created PDF in the server(NODEJS/Express) side, i am fairly new to java script and haven't seen any method to access the file.
I think i can use something like ${__dirname}/${user_details.Invoice_No_latest}.pdf but i am not sure if it is correct, any suggestions please
As can seen below the PDF that is generated (using html-pdf) is getting saved locally in the folder D:\Programming\Repo\JavaScript-Project\ec-server\22.pdf'
Once i get access to the file then i will use some thing similar as below code to save it to the database MySql
Snippet of code that i am looking to use afterwards
var jsfile = Buffer.concat(chunks);
var query = 'INSERT INTO `files` SET ?',
values = {
type: 'pdf',
data: jsfile
};
mysql.query(query, values, function(err) {
if (err) throw err; // TODO: improve
// do something after successful insertion
});
just looking if there is any simple way to access annd play with any file in the nodejs/Express that is stored locally there.

I found a way to use a locally stored file using the fs.readFile(/* Arguments Here */) function as shown here:
fs.readFile(`${__dirname}\\` + `${Invoice_No_Actual}` + `.pdf`, (err, data) => {
if (err) res.status(500).send(err);
else {
console.log(data);
res.contentType("blob");
res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`);
}
});

Related

Is this way to access mongodb in node.js acceptable?

I am new to programming and trying to experiment a bit, still struggling with the best way to access mongoDB from within my code. I've seen a few posts here on stack overflow but they more or less all require that the code required to load mongo is included in each and every .js file. I would like to avoid that in order to keep the code for accessing my DB in only one file.
Note that I am using the "mongo-factory" module.
Would the code below be acceptable?
I've created what I would call a "producer" of database objects, database.js
var mongoFactory = require('mongo-factory');
function Database(close,callback) {
mongoFactory.getConnection(<connection string>).then(function (database) {
callback(database.db(<db name>));
if(close) database.close();
}).catch(function (err) {
console.error(err);
});
}
module.exports = Database;
Then when I want to access the database from any of my files I could do the below, avoiding to introduce db-specific parameters and the mongo-factory requirement in here:
var Database = require('./database');
var callback_actOnDatabase = function (db) {
db.collection..... do something here
};
var d = new Database(false, callback_actOnDatabase);
instead of mongo-factoy use mongoose module to connect the database,model declaration also we dont intalise the db parameters again,please go through the link
https://www.npmjs.com/package/mongoose

Push new data to external JSON file

I'm trying to push a new object into an external Javascript document but I am having problems pulling in the JSON file to write to. I have an external, local file called check.json.
How do I call the external json file correctly in node?
var newData = JSON.parse(check.json);
newData.check.push({
cheap: $el.text()
});
check.json = JSON.stringify(newData);
You can use the Filesystem object to read and write to files. Specifically, the readFile and writeFile methods.
For example, to read:
fs.readFile('/path/to/my/json.json', function (err, data) {
if (err) throw err;
var newData = JSON.parse(data);
});
That said, flat files are not a good format for storing data and being accessed like a database. You can run into race conditions and lose data. You would be better off with a real database that will take case of that sort of thing for you.
SQLite gives you a simple file (but puts lots of protection in around it). If you really wanted JSON as the storage format then you could look at something like couchDB.

Express.js collection.find() return Object

I am wanted to display every documents stored in my mongodb. I tried following code which simply get collection.find() and display through res.send()
router.get('/index', function(req,res){
var db = req.db
var collection = db.get('usercollection')
var display = util.inspect(collection.find()));
res.send(display);
});
I expected it to display the actual document stored in mongodb. But instead, it displayed this object format:
{cold:{manager:{driver:[Object], helper:[Object], collection:[Object].....
Is there any other steps needed to display raw mongodb document?
If the library you are using is the official 10gen library, then you can't simply output collection.find() without unwinding it. The easiest way to do that for smaller datasets is
collection.find().toArray(function(err, results) {
if (err) {
// do something error-y
} else {
res.send( results );
}
});
If you post more of your code, and tag your question with the libraries you are using, you'll be able to get more targeted help. If the library you are using returns a promise, this is probably how you'd unwind it:
collection.find().then(function(results){
res.send(results);
}).catch(function(err){
console.error(err);
});

How to use the dropbox-js pullChanges method to get a file list of existing files

I am using dropbox-js to access a user's dropbox files. Please note that I am very new to this...
What I need to do, is to access existing files using dropbox-js. As I understand it, the pullChanges method should be used for this. This is how I currently have it:
client.pullChanges(null, function(error, results) {
if (error) {
return showError(error);
}
alert("Dropbox contains: " + results.shouldPullAgain); //just to test that something happens
});
I'm not sure if this is the correct way to make use of pullChanges, and then I need to know how to use results to actually get the file/folder information??

Renamed a file uploaded via Angularjs

In a nutshell, I need to rename files uploaded via Angular and Node and make that new name available to both the back and front ends (I think). What is the best practice for doing so?
I am using a file upload plugin (https://github.com/danialfarid/angular-file-upload) in an Angularjs app. The upload hits a route handled by Nodejs, uploads the file then, on success, angular saves the file name into a users account. However, if two people upload a file of the same name there will be a conflict so I need to rename each file (perhaps by adding a date and time).
My code works as follows:
Angular handles the upload, hitting a route that node can use.
Node move the file into place.
on success, angular saves the file name into the user's account.
It appears I cannot rename the file prior to uploading. If I rename the file via node after it has been moved into place I run into the issue of needing to get that new name back to angular for saving into the database. Not sure of the best way to approach this process.
Here is my current file upload code (works fine, just doesn't rename the file):
In Angular...
$scope.onFileSelect = function ($file) {
var photo = $file[0];
$scope.upload = $upload.upload({
url: '/upload/userphoto',
headers: {'Content-Type': photo.type},
file: photo,
method: 'POST'
}).progress(function (evt) {
//removed for brevity
}).success(function (data, status, headers, config) {
User.currentUser.user_profile_image = photo.name;
User.updateUser();
}).error(function (err) {
//removed for brevity
});
};
The post route, /upload/userphoto is matched in node with:
exports.uploadProfilePhoto = function(req, res) {
var callbacks = {};
callbacks.uploadSuccess = function(){
res.json('success');
};
callbacks.uploadFailure = function(err){
//removed for brevity
};
user.handleUserImageUpload(req.files, callbacks);
};
Which sets some callbacks and then hits handleUserImageUpload() which is:
this.handleUserImageUpload = function(params, callbacks) {
fs.readFile(params.file.path, function(err, data){
if(err){
callbacks.uploadFailure(err);
}
var newPath = path.resolve("./public/fileupload/userphotos/" + params.file.filename);
fs.writeFile(newPath, data, function(err) {
if(err){
callbacks.uploadFailure(err);
}
callbacks.uploadSuccess();
});
});
};
Which, assuming success, takes us back to the success handler of the first bit of Angular code above. I know I can rename the file in the handleUserImageUpload() method with fs.rename() like (just a hard coded example... I would actually take into account the file type and existing name plus add a random string or account identifier):
var renamedPath = path.resolve("./public/fileupload/userphotos/" + "abc123.jpg");
fs.rename(newPath, renamedPath);
But then I don't have that new name available when I go to save the file info into the user's account. I guess I could pass it back in the success callback? Is that the best way or am I missing something?
The solution turned out to be what I suspected... pass the value in the callback. So I added the following to handleUserImageUpload()...
// grab the extension
var fileExtension = '.' + params.file.filename.split('.').pop();
// rename the file with a sufficiently random value and add the file extension back
var renamedFile = Math.random().toString(36).substring(7) + new Date().getTime() + fileExtension;
//set up the new path for use in fs.rename()
var renamedPath = path.resolve("./public/fileupload/userphotos/" + renamedFile);
// Make it so
fs.rename(newPath, renamedPath);
// pass the new name to the callback
callbacks.uploadSuccess(renamedFile);
In the function that created the callbacks, uploadProfilePhoto(), I needed to make one important change, swap json with send (otherwise I would get quotation marks added to the value)
//res.json('success');
res.send(renamedFile);
Then I could access the this name as the data value in my Angular success handler.

Categories

Resources