如何從目錄中讀取文件並作為JSON發送到客戶端?

[英]How can I read files from directory and send as JSON to client?


I have logs files in server directory i wanted to display file names to client side so i have created readDirectory.js that is reading names correctly Now i am very new to node.js and i am trying to send json data to client but its not happening, How can i send log files name to client using express ?

我在服務器目錄中記錄文件我想向客戶端顯示文件名,所以我創建了正確讀取名稱的readDirectory.js現在我對node.js很新,我試圖將json數據發送到客戶端但是它不是發生了,如何使用快遞將日志文件名稱發送給客戶端?

readDirectory.js

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

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

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;
                });
        }
    }

});

2 个解决方案

#1


1  

your readDirectory.js should look like this:

你的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;

and your app.js should be like this:

你的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});
   });
});

Hope this Help !

希望這個幫助!

#2


2  

You have to put serialize the Logs array into json and send it back to client

您必須將Logs數組序列化為json並將其發送回客戶端

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

Or

要么

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/06/29/aea081f8c8195504da178ca5ecc794ff.html



 
  © 2014-2022 ITdaan.com 联系我们: