如何使用Node.js和Express将结果写入文件?

3
我使用node.js和express.js构建了一个基于elasticsearch的应用程序。这是一个非常简单的应用程序,其中包含一个搜索框。当您搜索一个查询时,它会以JSON格式输出结果。例如,如果我搜索关键词“white”,输出如下所示:http://i.stack.imgur.com/VHuWl.png 现在,我想将这个结果存储在一个文件中(例如output.json)。这是我的json文件:
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;

当我尝试使用node.js的writeFile方法时,出现了引用错误,显示"data"未定义。我的错误看起来像这样:http://i.stack.imgur.com/lwXfW.png 我无法弄清楚这个错误。是否有其他方法可以使用node.js和express将输出写入文件?
注:我已编辑了我的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;

当我运行这段 JavaScript 时,得到了如下输出: http://i.stack.imgur.com/rfBq0.png 我没有得到 JSON 输出,我的输出应该像这样: http://i.stack.imgur.com/VHuWl.png 我还在前端使用带有 JavaScript 的 ejs 文件(index.ejs),它看起来像这样:
<!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>

我需要从这个文件获取输出吗?

2个回答

1
我正在看这个代码块:

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

你在代码顶部声明了 path,但是在这个上下文中 data 似乎未定义。


是的。我已经声明了一个路径(output.json),我想将输出存储到那里。从我的发布方式可以看出,我想使用该数据附加到我的文件“output.json”中。 - Rose
正如@TGrif所指出的那样,您有两种方法可以解决这个问题。因为data在您的post方法中是有效的,所以您可以选择1.从post方法中调用writeFile,或者2.在文件顶部声明一个新变量来存储在post方法中传入的data - Andy Hoffman
你可能需要执行:JSON.stringify(data) - Andy Hoffman
我还在前端使用一个ejs文件来显示结果。我已经更新了我的帖子,包括那个文件。因为我在这里使用了JSON.stringify,所以我需要从这个ejs文件获取我的结果吗? - Rose
尝试不要改动服务器端的data,并在.ejs文件中尝试使用<%- JSON.stringify(data) %> - Andy Hoffman

1

data变量在这一点上未定义。您可以将fs.writeFile函数移动到searchModule.search调用中,如下所示:

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

或者在searchModule.search调用之前声明并设置变量,以便在范围内编写文件后可用。
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);
})

请检查我的更新帖子。我尝试使用您的第一种解决方案,但现在我的“output.json”看起来像这样http://i.stack.imgur.com/rfBq0.png - Rose
这已经好多了。根据你的数据而定,但也许你需要使用类似JSON.stringify(data)这样的东西来将你的数据转换成纯 JSON。 - TGrif
我还使用了一个ejs文件来显示前端的结果。我已经更新了我的帖子,包括该文件。因为我在这里使用了JSON.stringify,所以我需要从这个ejs文件中获取我的结果吗? - Rose

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接