如何从目录中读取文件并将其作为JSON发送给客户端?

我有服务器目录中的日志文件我想显示文件名到客户端,所以我已经创buildreadDirectory.js正在读取名称现在我是非常新的node.js ,我想发送json数据到客户端,但它不发生,我怎样才能发送日志文件名称客户端使用快递?

readDirectory.js

 var fs = require('fs'); var path = './Logs' var Logs = []; function readDirectory(){ fs.readdir(path, function(err, items) { Logs.push(items); /* console.log(items); for (var i=0; i<items.length; i++) { console.log(items[i]); }*/ }); return Logs; } exports.readDirectory = readDirectory; 

app.js

  var express = require('express'); var app = express(); var readDirectory = require('./readDirectory'); app.use(express.static(__dirname + "/public")); app.get('/logs',function(req,res){ res.send(readDirectory.readDirectory()); }); 

angularFactory.js

 angular.module('App').factory('DitFactory', function ($http) { 'use strict'; var data; return { data:"data from factory" getLogs: function () { return $http.get('/logs') .then(function (response) { return response.data; }); } } }); 

       

网上收集的解决方案 "如何从目录中读取文件并将其作为JSON发送给客户端?"

你的readDirectory.js应该是这样的:

 var fs = require('fs'); var path = './Logs' var Logs = []; function readDirectory(callback){ fs.readdir(path, function(err, items) { Logs.push(items); callback(Logs); }); } exports.readDirectory = readDirectory; 

和你的app.js应该是这样的:

 var express = require('express'); var app = express(); var readDirectory = require('./readDirectory'); app.use(express.static(__dirname + "/public")); app.get('/logs',function(req,res){ readDirectory.readDirectory(function(logFiles){ res.json({files : logFiles}); }); }); 

希望这个帮助!

你必须把Logs数组序列化成json并发送回客户端

 app.get('/logs',function(req,res){ res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(readDirectory.readDirectory())); }); 

要么

 app.get('/logs',function(req,res){ res.json(readDirectory.readDirectory()); });