[英]How to send fs.stat details in JSON format to front end AngularJS as a response?
我想要輸出獲取路徑列表並獲取每個文件名以及相關文件大小的輸出。 我在命令提示符下得到此輸出,但是我想要
節點以存儲此記錄並將響應發送到controller.js文件。
node_modules
上市
->控制器
-controller.js
-> index.html
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
var dir ='';
var result = [];
app.post('/filelist', function (req,res){
console.log(req.body);
dir = req.body.name;
res.end();
});
app.get('/filelist', function (req, res) {
console.log("I received a GET request")
fs.exists(dir, (exists) => {
if (exists) {
console.log("file exist " + dir);
fs.readdir(dir,function(err, items){
if (err) {
return console.error(err);
}
for (var i=0; i<items.length; i++) {
var file = dir + '/' + items[i];
console.log(file);
fs.stat(file, generate_callback(file));
}
});
}
else {
console.error('myfile does not exist');
res.json({message: 'Requested "'+dir+'" file or folder does not exist!'
});
}
});
function generate_callback(file) {
return function(err, stats) {
result = ({name:file.substring(6),Size:stats["size"]});
console.log(result);
res.json(result);
}
};
});
app.listen(3000);
console.log("Server running on port 3000");
controller.js
function AppCtrl($scope, $http){
console.log("Hello world from controller");
var refresh = function() {
$http.get('/filelist').success(function(response){
console.log("I got the data I requested");
$scope.filelist = response;
$scope.list = "";
$scope.msg = response.message;
});
};
$scope.searchPath = function() {
console.log($scope.contact);
$http.post('/filelist', $scope.list).success(function(response){
console.log(response);
refresh();
});
};
}
在res.json()
代碼中,在處理每個文件之前不要調用res.json()
。 一種方法是將目錄中的文件數傳遞給回調函數-
for (var i=0; i<items.length; i++) {
var file = dir + '/' + items[i];
console.log(file);
// pass the number of items in the directory to the callback here
fs.stat(file, generate_callback(file,items.length));
}
然后在回調中,將每個文件的結果添加到數組中(例如var results
),並且當該數組的length屬性等於目錄中的項目數時,調用res.json()
:
var results = [];
function generate_callback(file,numberOfItems) {
return function(err, stats) {
result = ({name:file.substring(0,6),Size:stats["size"]});
results.push(result);//add the result for the current file to the list of results
//when we have reached the last file, send the results in JSON format
if (results.length == numberOfItems){
res.json(results);
}
}
};
我在codeenv.com上運行了它 -在此處使用nodeJS 文件列表端點查看有角度的頁面-如果該頁面停止工作,則應該可以打開環境 ,單擊屏幕右上角的Launch按鈕,然后在終端運行node server.js
以啟動服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.