I am building an application on top of elasticsearch using node.js and express.
This is my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon'); //serve-favicon is Express middleware for serving a favicon. The advantage over just a normal favicon.ico on your public/ directory is that this module also deals with cache control. You can remove this module if you like because Express doesn't depend on it.
var logger = require('morgan');
var cookieParser = require('cookie-parser');//ookie-parser is Express middleware that helps you with handling cookies. Your request object will have a cookies object which you can acces use in your app. If your app doesn't use cookies you can leave it out.
var bodyParser = require('body-parser');//body-parser is Express middleware you probably want to use if you're doing anything with forms. It will add a body object to your request so that you can access POST parameters.
var routes = require('./routes/index'); //routes / users are two dummy pages to show you how routing works. You could do all the routing in app.js but it will get messy as your application gets bigger.
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));//These 2 lines set the views folder and the view engine. It tells Express to use the /views folder in your app directory.
app.set('view engine', 'ejs');//to use ejs engine
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev')); //This method tells the app to use the parameters you're giving it. logger('dev') logs the requests to the console as seen above. The dev parameter means it will log a lot of information about the request such as the method, status code and response time.
app.use(bodyParser.json()); //bodyParser.json() gives your app the ability to parse JSON. This is necessary for when you're sending data (which you probably will with a JavaScript application) in JSON format.
app.use(bodyParser.urlencoded({ extended: false }));//bodyParser.urlencoded({ extended: false }) allows your app to read data from URLs (GET requests). Extended is true by default but you'll need the querystring module.
app.use(cookieParser());//cookieParser() adds an cookie object to all the requests you get.
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);//The first parameter is the path, the second one is the function to execute. We separate the routes from the app.js because we don't want our app to be one big mess. Separating files in Node makes use of module.exports.
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {//In Express a 404 is not the result of an error but rather the app running out of options. Once the request doesn't match any of the routes, it will reach the following function.
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
This is my Javascript file(index.ejs) which is connecting to elasticsearch client:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<form action='/search-results' method='post'>
<input type="text" name="searchTerm" placeholder="your search term here">
<button type="submit"> SEARCH </button>
</form>
<ul>
<% if(locals.results) { %>
<pre>
<%= JSON.stringify(results,null,2) %>
</pre>
<% results.forEach( function( result )) %>
<% } %>
</ul>
</body>
</html>
This is my routes/index.js(JavaScript file):
var fs = require('fs');
//var path = "output.json";
var express = require('express'); //To make use of Express' routing capabilities you need to initiate a new Express Router.
var router = express.Router(); //To make use of Express' routing capabilities you need to initiate a new Express Router. get, put, post, delete, all
var searchModule = require('../search_module/search.js');
//There are two ways of using the router methods. You can define one route (for example /home) and attach the methods to it, or you can create a new method for each route.
/* GET home page. */
router.get('/', function(req, res) { //.get() - when you visit a website you make a GET request. You can get data from a URL in a GET request too.
res.render('index', { title: 'Express' });
});
router.post('/search-results', function(req, res) {//.post() is a method used everywhere for posting data to a server / app. You'll want to use this for submitting forms.
searchModule.search(req.body, function(data) {
res.render('index', { title: 'Express', results: data });
});
});
// fs.writeFile(path,data,function(err){
// if(err) console.error(err);
// })
module.exports = router;
This is how my browser looks like after I search for "white" query: https://i.stack.imgur.com/A10BO.png
I want to store this result(JSON result) in a file(output.json). I want to append the output to the local file. I tried using fs.writeFile method, but I was not successful. Is there any other way to store the results in a file?