Node.js File System passing values from browser - node.js

I know how I can simply write a file using nodes File System. However, I have a simple HTML page with an input. I want to use javascript to get the value of the input submitted by a user and take this value and add it into the file written by node.
For example:
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text' + <VARIABLE>, function (err) {
if (err) throw err;
console.log('Replaced!');
});
Where is the value being pulled in from the javascript on the input.

Assuming you are using Express, the req object has a property called query that allows you to access the parameters sent with a request.
app.get('/myroute/', function(req, res) {
console.log(JSON.stringify(req.query)); //log entire query object
fs.writeFile('mynewfile3.txt', 'This is my text' + req.query.myvariable, function(err) {
if (err) throw err;
console.log('Replaced!');
res.json({
success: true,
message: "File written"
});
});
});

Related

Node.Js wont Upload file to Directory

I want to simulate an upload in Node.js REST api.
I want to make the REST api upload the files to a directory and then save the URL of the saved file to the database table.
For some reason, I dont know of , he just tells me , "No Files uploaded" But looking thru, everything seems okay.
I am testing thru Postman, so thats where i seem to be getting the output and what it tells me.
My code is looking like this:
app.post('/api/createpost', function (req,res){
if(!req.files) return res.status(400).send('No Files uploaded');
const {foo} = req.files;
const uploadTo = `postimages/${foo.name}`;
foo.mv(uploadTo, (err) =>{
if(err) return res.status(500).send(err);
//push data to mysql Db
var username = req.body.username;
var imgUrl = 'http://localhost/'+uploadTo;
var post = req.body.post;
dbConn.query('INSERT INTO instagramclonedbposts SET ?', [username, imgUrl, post], function(error, results, fields){
if(error) throw error;
return res.send({error:false, message: 'Post Created'});
});
});
});
Testing in Postman, I have this :
Could there be something i am missing?

Capture a JSON GET response in a variable?

I'm using request-promise to get data from an endpoint that I have.
Is it posible to 'capture' a json response in a variable to use it anywhere?
try{
var gamer = '';//variable to capture json data
var options = {
uri: 'http://localhost:4000/gamers/'+gamer._id+'/find',
json: true
};
RequestPromise(options)
.then(function (data) {
gamer = data;//capturing response
})
.catch(function (err) {
console.log("Error saving player data !");
});
.... do something with gamer ....
}catch(err){
res.status(500).send({
message: err.message || 'An error occurred generating player teams !'
});
}
The reason that I need to do this is because actually I don't have access to the database to get that information, so my only option is to consume an API to get information through collections id's.
Your doing a lot of things correctly already. The issue is your gamer variable will get assigned the value you expect first when your promise resolves. There are many ways to skin this cat, but to get you started try performing whatever you want to perform on the gamer variable in .then(), like this:
try{
var gamer = '';//variable to capture json data
var options = {
uri: 'http://localhost:4000/gamers/'+gamer._id+'/find',
json: true
};
RequestPromise(options)
.then(function (data) {
gamer = data;//capturing response
// here is the rigth place perofrm operations on the answer, as this part of the code gets executed after promise reolves. BTW. Then you don't need variable gamer.
})
.catch(function (err) {
console.log("Error saving player data !");
});
// here is not the right place to do something with gamer as this is executed as soon as promise is initialized, not as it resolves. This means your variable will have initial value here
}catch(err){
res.status(500).send({
message: err.message || 'An error occurred generating player teams !'
});
}

Saving HTTP GET response to a file in a express/node app

I have an express/node app which exposes a GET end point via express router something like /api/user. The response is a JSON and i want to download the JSON to a file when i hit localhost:8080/api/user.
I tried with res.download but not sure how to handle the response data with it. This could be a duplicate question but i cannot find an example especially for this use case.
When the end point is invoked in browser it should prompt for download and then should get downloaded to the default location.
router.route('/user')
.get((req, res) => {
MyService.get().then((result) => { // the get method resolves a promise with the data
// Prompt for download
}).catch((err) => {
console.log(err);
res.status(500).json({
status: 500,
data: err
});
});
});
So i was able to do this in one of the 2 ways below,
router.route('/user')
.get((req, res) => {
MyService.get().then((result) => {
res.attachment('users.csv');
/*or you can use
res.setHeader('Content-disposition', 'attachment; filename=users.csv');
res.set('Content-Type', 'text/csv');*/
res.status(200).send(result);
}).catch((err) => {
console.log(err);
res.status(500).json({
status: 500,
data: err
});
});
});
If I understand correctly, you want to save the sent data of /api/user to a file that you are sending in a route?
var fs = require('fs')
app.get("/api/user", function(req, res){
var data = fromDb()
fs.writeFileSync("/tmp/test", JSON.stringify(data))
res.send(data)
})
You need to write the JSON response to a file using the node filesystem module. You can check out an example here Writing files in Node.js
If I got you right then You can try Content-Type and Content-disposition headers like below:
res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':attachment; filename={your_file_name}.json});
res.end(data);
NOTE :
data in res.end(data) is your json data.
{your_file_name}.json is your actual file name , give it any name.

How to upload a file and then display its contents in Node.Js Express app?

I'm trying to find an answer to this question for a long time: I need to upload a text/html file through my Node.Js express app and to save its contents into a variable for further treatment.
I can make the multipart form, of course, and post the content, but what I can access so far is only req.files which contains information about the file, but not the actual contents.
How do I get the actual text/html contents from the file?
I don't want to save it to my server, just pass on the content to my app and get rid of the file, so I don't want to use a module like formidable.
Can anyone help please?
Thank you!
The file is saved by default in a temporary folder (likely /tmp). You need to open the file, read its contents, and then delete it.
You'll want to use this API: http://nodejs.org/api/fs.html
And you could do this:
fs = require('fs');
fs.readFile(req.files.path, function (err, data) {
if (err) throw err;
// data will contain your file contents
console.log(data)
// delete file
fs.unlink(req.files.path, function (err) {
if (err) throw err;
console.log('successfully deleted ' + req.files.path);
});
});
Use multer https://github.com/expressjs/multer with the option inMemory: true.
As a crude example you'll want to do something like this.
app.post('test', function(req, res, next) {
var result = '';
multer({
inMemory: true,
onFileUploadData: function(file, data) {
result += data;
},
onFileUploadComplete: function(file) {
console.log(result); // This is what you want
}
})(req, res, next);
});

app.render() not displaying in browser

I'm trying to use app.render() to display a jade file in the browser. In the following code, the html is displayed to the console correctly, but the browser never shows the related file.
app.render('unavailable', {title: 'Unavailable'}, function(err, html){
console.log(html);
});
EDIT:
I have this handler:
app.get('/unavailable', display.unavailable);
Then beneath this code in the same file (app.js) I have this:
sql.open(connStr, function(err, sqlconn){
if(err){
console.error("Could not connect to sql: ", err);
else
conn = sqlconn; //save the sql connection globally for all client's to use
});
So, what I want to happen is when the err happens with the SQL connection, the /unavailable handler is executed and a static html page is displayed that says the service is down. However, because the error occurs on the server, and not the client, I don't have access to a response object at that time. I'm trying to artifically manufacture the client 'redirecting' to /unavailable in their browser to see the message.
Obviously you don't send the html to the browser. Use res.render inside a route without callback, i.e.
res.render('unavailable', {title: 'Unavailable'});
or send the result of rendering like here:
app.render('unavailable', {title: 'Unavailable'}, function(err, html){
console.log(html);
res.send(html);
});
Read more about the difference here:
What's the difference between "app.render" and "res.render" in express.js?
save a global var sqlOK = false, set it in sql.open callback, and redirect to /unavailable if you get a request while sqlOK is not true. you were also missing brackets around the else statement.
var sqlOK = false;
app.get('/unavailable', display.unavailable);
app.get('*', function(req, res, next){
if(!sqlOK){
return res.redirect('/unavailable');
//return res.send(500)
};
next();
});
sql.open(connStr, function(err, sqlconn){
if(err){
console.error("Could not connect to sql: ", err);
} else {
conn = sqlconn; //save the sql connection globally for all client's to use
sqlOK = true
}
});

Resources