【问题标题】:How to write result in a file by using node.js and express?如何使用 node.js 和 express 将结果写入文件?
【发布时间】:2016-08-29 01:17:01
【问题描述】:

我在 elasticsearch 之上使用 node.js 和 express.js 构建了一个应用程序。这是一个带有搜索框的非常简单的应用程序。当您搜索查询时,它会以 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 方法时,我收到一个显示“数据”未定义的参考错误。我的错误如下所示: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>

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

【问题讨论】:

    标签: javascript node.js express elasticsearch


    【解决方案1】:

    此时未定义data 变量。 您可以像这样在 searchModule.search 调用中移动您的 fs.writeFile 函数:

    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”看起来像这样i.stack.imgur.com/rfBq0.png
    • 这已经好多了。取决于您的数据,但也许您必须使用 JSON.stringify(data) 之类的东西将您的数据转换为纯 JSON。
    • 我也在使用前端的 ejs 文件来显示结果。我已更新我的帖子以包含该文件。我是否需要从此 ejs 文件中获取结果,因为我在这里使用了 JSON.stringify。
    【解决方案2】:

    我在看这个块:

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

    您已在代码顶部声明了path,但data 在此上下文中似乎未定义。

    【讨论】:

    • 是的。我已经声明了一个路径(output.json),我想在其中存储我的输出。从我的 post 方法中可以看出,我想使用该数据附加到我的文件“output.json”。
    • 正如@TGrif 指出的那样,您有两种方法可以解决这个问题。因为data 在您的 post 方法中有效,您可以 1. 在 post 方法中从该位置调用 writeFile 或 2. 在文件顶部声明一个新变量,该变量存储您的 post 方法中的 data .
    • 您可能需要这样做:JSON.stringify(data)
    • 我也在使用前端的 ejs 文件来显示结果。我已更新我的帖子以包含该文件。我是否需要从此 ejs 文件中获取结果,因为我在这里使用了 JSON.stringify。
    • 尝试单独保留服务器端data,并从.ejs 文件中尝试&lt;%- JSON.stringify(data) %&gt;
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多