2016-06-29 44 views
6

我有服務器目錄中的日誌文件我想顯示文件名稱到客戶端,所以我創建了readDirectory.js,正在讀取名稱現在我很新node.js,我試圖發送json數據給客戶端,但它沒有發生,如何使用快遞將日誌文件名稱發送給客戶端?如何從目錄中讀取文件並將其作爲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; 
       }); 
     } 
    } 

}); 

回答

1

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

希望這個幫助!

+0

感謝它的工作,我感謝你的幫助! – hussain

2

你必須把序列化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()); 
}); 
+0

仍然我沒有看到數據我不知道爲什麼 – hussain

+0

嘗試使用Web瀏覽器訪問JSON嗎?或者你可以嘗試'console.log(response)' –

+0

我認爲第一個地方我沒有從'readDirectory.js'獲取數據到'app.js'由於某種原因我放棄了它,我看到Logs數組中的4個項目在' readDirectory'函數,但它沒有被傳遞給'app.js' – hussain

相關問題