简体   繁体   中英

How to write result in a file by using node.js and express?

I've built an application using node.js and express.js on top of elasticsearch. This is very simple application with a search box. When you search for a query, it prints result in JSON format. For eg, if I search for keyword "white", the output looks like this: http://i.stack.imgur.com/VHuWl.png

Now I want to store this result in a file(for eg output.json).This is my json 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;

When I tried using writeFile method of node.js, I am getting an Reference error showing that "data" is not defined. My error looks like this: http://i.stack.imgur.com/lwXfW.png

I am not able to figure out this error. Is there any other way to write the output to a file by using node.js and express?

Edit: I edited my javascript

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) {
    fs.writeFile(path,data,function(err){
       if(err) console.error(err);
    })
    res.render('index', { title: 'Express', results: data });
  });
});
module.exports = router;

But when I ran this javascript, I got this output: http://i.stack.imgur.com/rfBq0.png

I am not getting the JSON output. My output should look like this: http://i.stack.imgur.com/VHuWl.png

I am also using an ejs file with my javascript for the frontend(index.ejs) which looks like this:

<!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>

Do I need to get output from this file?

I'm looking at this block:

fs.writeFile(path,data,function(err){
     if(err) console.error(err);
})

You've declared path at the top of your code, but data appears to be undefined in this context.

The data variable is not defined at this point. You can move your fs.writeFile function in the searchModule.search call like this:

searchModule.search(req.body, function(data) {
    fs.writeFile(path,data,function(err){
       if(err) console.error(err);
    })
    res.render('index', { title: 'Express', results: data });
});

or declare your variable before and set it in the searchModule.search call, to be disponible after in the scope to write your file:

var fileData;

searchModule.search(req.body, function(data) {
    fileData = data;
    res.render('index', { title: 'Express', results: data });
});

fs.writeFile(path,fileData,function(err){
   if(err) console.error(err);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM