Node Js Express遍历数组

Node Js Express Iterate through array

本文关键字:数组 遍历 Express Js Node      更新时间:2023-09-26

我将shell命令的STDOUT拆分为一个数组,并将其传递给hogan视图引擎。

下面是来自路由器文件- index.js

/* Test Shell Execute. */
router.get('/shell', function(req, res){
  exec('ls -1', function (error, stdout, stderr) {
       result = stdout.toString().split("'n");
       res.render('shell', { title: "File Explorer",
          array1: result[0],
          array2: result[1],
          array3: result[2],
          array4: result[3],
          array5: result[4],
          error: error,
          stderr: stderr 
     });
  });
});

这工作得很好,但是,而不是手动通过数组中的每个项目发送,我想在视图端迭代项目,然后输出。然而,我正在使用Hogan视图引擎,它似乎根本无法识别脚本标签。

这是来自我的视图shell。hj文件。

<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome to {{ title }}</p>
     <p>Array1 =  {{ array1 }}</p>
     <p>Array2 =  {{ array2 }}</p>
     <p>Array3 =  {{ array3 }}</p>
     <p>Array4 =  {{ array4 }}</p>
     <script>
     for(var i = 0; i > result.length; i++  ) {
         document.write('<p>' + result[i] + '</p>')
     }
     </script>
  </body>
</html>
问题:我做错了什么,最好/最简单的方法是什么?

因为hogan.js是基于mustache.js的,所以最好将数组转换为对象。试试这个:

router.get('/shell', function(req, res){
  exec('ls -1', function (error, stdout, stderr) {
    result = stdout.split("'n"),
             filesArray = [];
    result.map(function (file, index) {
      filesArray.push({index: ++index, file: file});
    });
    res.render('shell', { title: "File Explorer",
      result: filesArray,
      error: error,
      stderr: stderr 
    });
  });
});

并且,在你的模板中:

<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome to {{ title }}</p>
    <ul>
      {{#result}}
      <li>Array{{index}} = {{file}}</li>
      {{/result}}
    </ul>
  </body>
</html>