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
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;
});
}
}
});
push(newData); To write this new data to our JSON file, we will use fs. writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it.
readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
You have to put serialize the Logs
array into json and send it back to client
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());
});
your readDirectory.js should look like this:
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:
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With