how to write a file on one controller and read the same in another controller in Node.js - node.js

I want to implement a functionality in nodejs. I have two different controllers in my node application. I has the responsibility to store the file (abc.xlsx) into local folder(mylocation) using fs module and i have done it successfully. And in my another controller i have to read the locally stored file(abc.xlsx).
Is it possible. Everytime i want to write a file from one controller and read the same from another controller. I have tried something as like the following..
exports.controller1 = function(req,res){
if(req.files.file){
fs.readFile(req.files.file.path,function(err,data){
var fileName = req.files.file.name;
getfileName(fileName);
some logic goes here......
});
}
}
function getFileName(fileName){
console.log(fileName);
}
exports.controller2 = function(req,res){
getFileName(fileName);
var filePath = fileName;
my logic goes here...
}
Need some help to get the fileName or the filePath to read a file
Thanks in advance.

Related

Node.js reads the file but does not write JSON in the HTML

I'm currently running Node.js by Browserify for my website.
It reads the JSON file and I get the message through MQTT.
But the problem is that it seems like writefile does not work.
(Running this as node test.js in the terminal works by the way).
What is wrong with my code?
Moreover, Is this the best way to store any user data?
Thank you so much in advance.
Here's some part of my code
var fs = require("fs");
var path = require("path");
let newFile = fs.readFileSync('/home/capstone/www/html/javascript/test.json');
function testT() { //THIS WORKS FINE
let student0 = JSON.parse(newFile);
var myJSON = JSON.stringify(student0);
client.publish("send2IR", myJSON);
response.end();
};
function write2JSON() { //PROBLEM OF THIS CODE
const content = 'Some content!'
fs.writeFileSync('/home/capstone/www/html/javascript/test.json', content)
};
document.getElementById("blink").addEventListener("click", publish);
document.getElementById("write").addEventListener("click", write2JSON);
You cann't write directly for security reasons. For other hand you can use a server as API to do the filye system tasks and in the client only trigger the events.
This post is very related with your problem:
Is it possible to write data to file using only JavaScript?

Rename file before upload using remote hooks in loopback component storage

I am having difficulty in renaming a file before upload in loopback component storage. As it seems, loopback does'nt provide a built-in option for the same. For uploading from a angular form, I have used the angular uploader beforeupload method to change the filename using following method:
this.fileExtension = '.' + item.file.name.split('.').pop();
item.file.name = Math.random().toString(36).substring(7) + new Date().getTime() + this.fileExtension;
Is it possible to perform the same operations in before remote hook of the upload method in loopback component storage? My intention is to do the same file name change operation for api requests coming from mobile devices. If a remote hook cannot do the same, is there any other method for achieving the same result? Thanks in advance!
Say you have storage DS defined in datasources.json.
You can do it in a boot script :
//server/boot/any.js
module.exports = function(app){
app.dataSources.storage.connector.getFilename = function (file, req, res) {
//file.name is original filename uploaded
var filename = req.query.filename || 'general.ext';
return filename;
}
};
and add filename in the upload url.
e.g : /containers/my-container/upload?filename=profile.jpg

Server Side rendering in mongo with dust

Is it possible to fetch data from MongoDB and render a html template on the server side itself for a node-js project?
As of now in my serverside js file I've done the following.
//Failing array will be populated by a db.find later on.
var failing = [
{ name: "Pop" },
{ name: "BOB" }
];
/*Now i have to send a mail from the server for which I'm using nodemailer.
Where do i store the template ? This is what I've done in the same file */
var template = "<body>{#failing} <p>{.name}</p> {/failing}</body>"
// Add this as the body of the mail and send it.
I'm not sure how to render the data and how to get it displayed. I'm aware storing the template in the variable isn't right but I'm not sure what else to do.
If your template is that short, you can store it in a variable without problem. Obviously, you can store it in a file also.
Let's say you decide to store it in a file index.dust:
<body>{#failing} <p>{.name}</p> {/failing}</body>
Now, in your node controller you need to load the file and generate the html content from it:
const fs = require('fs');
const dust = require('dustjs-linkedin');
// Read the template
var src = fs.readFileSync('<rest_of_path>/index.dust', 'utf8');
// Compile and load it. Note that we give it the index name.
var compiled = dust.compile(src, 'index');
dust.loadSource(compiled);
// Render the template with the context. Take into account that this is
// an async function
dust.render('index', { failing: failing }, function(err, html) {
// In html you have the generated html.
console.log(html);
});
Check the documentation in order not to have to compile the template every time you have to use it.

Node.js check if multiple files exists with unspecific extension

I have using node.js to develop a application that grabs an user's avatar file saved I the file system.
var fs = require('fs');
fs.exists(__dirname + "/../public/uploaded/users/" + user.username + "/avatar.png", function(exists){
if(exists){
//...
} else {
//...
}
}
But this checks only if avatar.png exists. Some avatar file such as avatar.gif or avatar.jpg could also be grabbed.
I know I can put three level of if statements inside if(exists) but I want to know a better way.
Thanks,
Dennis
I'm not sure if there is an easy native method but this library seems like it would do what you are looking for: https://github.com/isaacs/node-glob

Connect and Express utils

I'm new in the world of Node.js
According to this topic: What is Node.js' Connect, Express and “middleware”?
I learned that Connect was part of Express
I dug a little in the code, and I found two very interesting files :
./myProject/node_modules/express/lib/utils.js
and better :
./myProject/node_modules/express/node_modules/connect/lib/utils.js
These two files are full of useful functions and I was wondering how to invoke them correctly.
As far, in the ./myProject/app.js, that's what I do:
var express = require('express')
, resource = require('express-resource')
, mongoose = require('mongoose')
, expresstUtils =
require('./node_modules/express/lib/utils.js');
, connectUtils =
require('./node_modules/express/node_modules/connect/lib/utils.js');
But I found it a little clumsy, and what about my others files?
e.g., here is one of my routes:
myResources = app.resource(
'myresources',
require('./routes/myresources.js'));
and here is the content of myresources.js:
exports.index = function(req, res)
{
res.render('./myresources.jade', { title: 'My Resources' });
};
exports.show = function(req, res)
{
fonction resourceIsWellFormatted(param)
{
// Here is some code to determine whether the resource requested
// match with the required format or not
// return true if the format is ok
// return false if not
}
if (resourceIsWellFormatted(req.params['myresources']))
{
// render the resource
}
else
{
res.send(400); // HEY! what about the nice Connect.badRequest in its utils.js?
}
};
As you can see in the comment after the res.send(400), I ask myself if it is possible to use the badRequest function which is in the utils.js file of the Connect module.
What about the nice md5 function in the same file?
Do I have to place this hugly call at the start of my myresources.js to use them?:
var connectUtils =
require('../node_modules/express/node_modules/connect/lib/utils.js');
or, is there a more elegant solution (even for the app.js)?
Thank you in advance for your help!
the only more elegant way i came up with is (assuming express is inside your root "node_modules" folder):
require("express/node_modules/connect/lib/utils");
the node installation is on windows, node version 0.8.2
and a bit of extra information:
this way you don't need to know where you are in the path and be forced to use relative paths (./ or ../), this can be done on any file nesting level.
i put all my custom modules inside the root "node_modules" folder (i named my folder "custom_modules") and call them this way at any level of nesting:
require("custom_modules/mymodule/something")
If you want to access connect directly, I suggest you install connect as a dependency of your project, along with express. Then you can var utils = require('connect').utils.

Resources