NodeJS access variable from mongodb & write to JSON file - json

I need to write a field from my mongodb database to a json file. Using node js. How to go about it? I haven't found anything helpful.

Try this
var exportDocuments = function (db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function (err, docs) {
require('fs').writeFile('yourFileName.json', JSON.stringify(docs), function (error) {
if (error) return callback(error);
callback();
});
});
}

Related

node.js returning contents of a file using request module

I was learning how to read json data (for the walkscore.com api) in Node.js and I found the request module. I know how to make it perform an action within the "request" block. However, I am calling it within a function and I want the function to return the json data. How would I be able to simply access the "body" variable inside the function, but outside the request block?
var request = require("request")
function loadWalkScore(lat, lon, address, name, state) {
var address = encodeURI(address)
var url = "http://api.walkscore.com/score?format=json&address=" + address
url += "&lat=" + lat + "&lon=" + lon + "&wsapikey=" + wsapikey
request(url, { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
// somehow make loadWalkScore() function return <body>
});
}
You would want to have loadWalkScore accept a callback argument, and call it within your request callback. When writing Node code, your functions rarely actually return the data you asked for, they'll either accept (and eventually invoke) a callback that you provide, or return Promises (which eventually resolve with the requested data). This is how to work with async operations like an HTTP request.
Possibly something like:
function loadWalkScore(lat, lon, address, name, state, cb) {
....
request(url, { json: true }, (err, res, body) => {
if (err) {
console.log(err);
cb(err);
} else {
cb(null, body);
}
});
Then call it like:
loadWalkScore(...args..., function (err, body) {
console.log('body:', body);
})

Render JSON data onto ejs view with Expressjs

I am trying to get 2 values from a JSON file on to the webpage.
obj["fruit"] and obj["thyroid"]. I use ejs as the template view engine and expressjs.
The below method says "fruit" and "thyroid" are undefined. The console.log works though.
app.post('/top', function (req, res) {
var obj;
fs.readFile('./object.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
console.log(obj["fruit"]);
console.log(obj["thyroid"]);
});
res.render(
'disp.ejs',
{
food: obj["fruit"]
name: obj["thyroid"]
}); // render
});
fs.readFile(path[, options], callback) is the asynchronous way to read a file. The way your code is setup node will start reading the file and immediately then call res.render before the file data is finished reading.
If you put the res.render inside the callback it will only be called when the file is finished reading and the data variable has what you need.
for example:
app.post('/top', function (req, res) {
var obj;
fs.readFile('./object.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
console.log(obj["fruit"]);
console.log(obj["thyroid"]);
res.render(
'disp.ejs',
{
food: obj["fruit"]
name: obj["thyroid"]
}); // render
});
});

Analyzing json using Watson API Nodejs

I would like to analyze a JSON file I dynamically create with Watson's tone analyzer. I would like it to read the file, then analyze it.
How can I make the tone_analyzer.tone method read the file? Thank you.
app.get('/results', function(req, res) {
// This is the json file I want to analyze
fs.readFile('./output.json', null, cb);
function cb() {
tone_analyzer.tone({
// How can I pass the file here?
text: ''
},
function(err, tone) {
if (err)
console.log(err);
else
console.log(JSON.stringify(tone, null, 2));
});
console.log('Finished reading file.')
}
res.render('results');
})
Your callback is missing a couple of arguments (error, data) (see the node fs documentation for more info). Data is the content of your file and would go where you are sending the text.
Try something like this:
app.get('/results', function(req, res) {
// This is the json file I want to analyze
fs.readFile('./output.json', 'utf8', cb);
function cb(error, data) {
if (error) throw error;
tone_analyzer.tone({
// How can I pass the file here?
text: data
},
function(err, tone) {
if (err)
console.log(err);
else
console.log(JSON.stringify(tone, null, 2));
});
console.log('Finished reading file.')
}
res.render('results');
})
Thanks to user Aldo Sanchez for his tip. I converted the input into JSON first since fs was returning it in the form of buffer data. Also, I made it search for the specific value in the key/value pair and return that content, instead of returning the whole string. This can be directly inputted to Watson's tone analyzer.
var data = fs.readFileSync('./output.json', null);
JSON.parse(data, function(key, value) {
if (key == "message") {
cb(value);
}
function cb(value, err) {
if (err) throw err;
tone_analyzer.tone({
text: value
},
function(err, tone) {
if (err)
console.log(err);
else
console.log(tone);
});
}
console.log('Finished reading file.')
});

Create databases connection on startup - sails.js

I know you can use Waterline and the models approach, but the issue is that I have to access more than one database to generate a response. Besides the models approach makes it difficult to think on a solution due to the fact that the data is joined and infered from different tables under the different databases.
Therefore, I would like to know how can I open a DB connection using the mysql or mysql2 native driver and reuse it all over the app. Where is the most suitable place, a hook, etc.? How can I close them when the app goes down?
TA
A custom hook will be the best for you. For Redis, I created one like this:
api/hooks/redis/index.js
var redisModule = require('redis');
module.exports = function connectToRedis(sails) {
return {
connectToRedis: function (callback) {
var hook = this;
var config = sails.config.connections.redis;
var redisClient = redisModule.createClient(config.port, config.host);
hook.initAdapters();
redisClient.on('connect', function () {
sails.log.verbose('Connection to redis was succesfull!');
// select db
redisClient.select(config.db, function (err) {
if (err) {
return callback(err);
}
sails.adapters.redis = redisClient;
callback();
});
});
redisClient.on('error', function (error) {
sails.log.error(error);
callback();
});
},
initAdapters: function () {
if (sails.adapters === undefined) {
sails.adapters = {};
}
},
// Run automatically when the hook initializes
initialize: function (cb) {
var hook = this;
hook.connectToRedis(function() {
cb();
});
},
};
};

Angular Seed project, set index.html by default

I am using the Angular Seed project to build a simple website. When i start the node server and enter the url at localhost:8000, it serves up the directory contents. I would like it to serve up the index.html file but would like to do this without a redirect.
I believe that I need to modify the following function and that I should change the code for the isDirectory check but I'm not sure if that is the correct way to go about doing this. Any suggestions would be appreciated.
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
Update #1
I have two screenshots to clarify. The first image is what I currently get, the second image is what I want.
What I Get
What I Want
Update #2
Using the link to Restify below I found the following example which is exactly what I needed.
var server = restify.createServer();
var io = socketio.listen(server);
server.get('/', function indexHTML(req, res, next) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
next(err);
return;
}
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(data);
next();
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(8080, function () {
console.log('socket.io server listening at %s', server.url);
});
The angular-seed project is a starting point for the client, but not really for the server side.
They included a simple web-server node script without dependencies. This way you don't need npm or other modules.
For the server side you can use node with connect/express or any other web server/language.
You just need to make rest services and serve some static html.
Since you have already installed Node restify may be something for you.
Update: I created a basic sample for using the angular-seed with restify:
https://github.com/roelandmoors/restify-angular-seed