Node / statSync issues - javascript

I'm trying to log an array of numerically named sub-directories in "e:\subdirectory\" by using fs.statSync but I keep getting the error "module.exports" is not a function; to my understanding, this is exactly how I'm supposed to export the data
I'm using the synchronous version because I want the array to finish populating before it's exported.
this is for a "proof of concept", I plan on serving an html doc and pushing this array to an input field
here is the code...
checke.js
var fs = require('fs');
function checkE() {
for (var i = 1, accts = [], path = "e:\\subdirectory\\"; i <10000; i++ ) {
var target = fs.statSynch(path + i.toString())
if (target.isDirectory()) { accts.push(i) }
}
}
module.exports(checkE)
init.js
var checke = require('./checke.js')
console.log(checke)

You need to assign something to module.exports not call it like a function. module.exports is an object
checke.js
var fs = require('fs');
module.exports = {
checkE: function checkE() {
var accts = [];
var path = 'e:\\subdirectory\\';
for (var i = 1; i <10000; i++ ) {
var target = fs.statSync(path + i.toString())
if (target.isDirectory())
accts.push(i);
}
return accts;
}
}
init.js
var checke = require('./checke.js');
checke.checkE();

Related

check if array contains string in node.js

I try to write a code that will create a file with an amount of random jokes using this npm and Environment Variables in an env file but I can't get it to work.
here is the code:
let oneLinerJoke = require("one-liner-joke");
require("dotenv").config();
let fs = require("fs");
var getRandomJokeWithTag = oneLinerJoke.getRandomJokeWithTag(
`${process.env.JOKE_SUBJECT}`
);
let arrayJokes = [];
let i = 0;
let counter = 0;
let amount = parseInt(`${process.env.JOKE_AMOUNT}`);
while (i <= amount) {
let joke = oneLinerJoke.getRandomJokeWithTag(process.env.JOKE_SUBJECT);
joke = joke.body.replace(",", "");
if (arrayJokes.includes(joke)) {
arrayJokes.push((joke + "\n"));
i++;
}
}
const createFile = fs.writeFileSync('./created_files/jokes.txt', arrayJokes.toString().replace(/,/g, ""));
Add __dirname to specify the directory.
const createFile = fs.writeFileSync(__dirname + '/created_files/jokes.txt', arrayJokes.toString().replace(/,/g, ""));

How to define object in node js

I am trying to assign a value to an object, but when I try to display it always returns [].
here is a piece of my code
const exspress = require("express");
const aplication = exspress();
//body parser for informaton monggo
const bodyparser = require("body-parser");
//configuration for node aplication
aplication.use(
bodyparser.urlencoded({
extended: false
})
);
const mongose = require("mongoose");
const router = exspress.Router();
const PingModel = mongose.model("Ping");
const ping = require("ping");
var tcpp = require("tcp-ping");
var obj = Array();
var a = 0;
var b = pingtime;
for(a; a<b; a++){
ping.promise.probe(host).then(function(data) {
const storePing = new PingModel();
storePing.hostPing = host;
storePing.hostIp = data.numeric_host;
if (data.alive) {
storePing.hostStatus = "Ok";
} else {
storePing.hostStatus = "Not_ok";
}
if (data.alive) {
storePing.hostLatency = "true";
} else {
storePing.hostLatency = "false";
}
storePing.save();
window.obj = storePing
// return this.obj[a] = storePing;
});
console.log(obj);
}
module.exports = router;
Can you guys tell me how to define an object and fill it with data/value that I use it in separate code/function?
try changing window.obj to obj as your obj is only a variable, it is not on a window object
also, when declaring your object, you have declared it as an Array. If you want an Object, you can use var obj = {};, though are are reassigning it anyway with storePing
also, you would need to move your console.log into the then callback of the promise, since it is async code you have - at the minute, your console.log will fire before the then callback of the promise has executed and thus obj would not yet have the value your are expecting
Something a long the lines of -
const router = exspress.Router();
const PingModel = mongose.model("Ping");
const ping = require("ping");
var tcpp = require("tcp-ping");
var obj = {}; // NOTE, object instead of array, though this gets reassigned anyway, so doesn't really matter
var a = 0;
var b = pingtime;
for(a; a<b; a++){
ping.promise.probe(host).then(function(data) {
const storePing = new PingModel();
storePing.hostPing = host;
storePing.hostIp = data.numeric_host;
if (data.alive) {
storePing.hostStatus = "Ok";
} else {
storePing.hostStatus = "Not_ok";
}
if (data.alive) {
storePing.hostLatency = "true";
} else {
storePing.hostLatency = "false";
}
storePing.save();
obj = storePing // <-- NOTE, no window object
console.log(obj); // <-- NOTE, logging inside the then callback
// return this.obj[a] = storePing;
});
}
module.exports = router;

.log file read and convert to json

I have .log file and I need to get this file in javascript and convert to JSON. I try this
var j= readTextFile("log991/sensorData.log");
console.log(j);
var jsonnn = JSON.stringify(j);
console.log(jsonnn);
But I only get path in console log. Is there any way to make this?
this is how .log file looks
2018-04-03 15:47:58,873 INFO log(17) batteryCurrent=-0.45, solarCurrent=3.27,
hybridCurrent=0, batteryVoltage=12.88, solarVoltage=13.09
2018-04-03 15:48:00,074 INFO log(17) batteryCurrent=-0.45, solarCurrent=3.27,
hybridCurrent=0, batteryVoltage=12.88, solarVoltage=13.09
2018-04-03 15:48:01,274 INFO log(17) batteryCurrent=-0.4, solarCurrent=3.28,
hybridCurrent=0, batteryVoltage=12.89, solarVoltage=13.1
thnx
try this code used synchronous version
const fs = require('fs');
var text = fs.readFileSync('/somepath/a.txt','utf8')
console.log (text)
try this code to convert into json
const fs = require('fs');
var text = fs.readFileSync('/somepath/a.txt','utf8')
array = text.split("\n")
var dataArray = [];
for(var i=0; i<array.length; i++){
if(array[i] == ''){continue}
let tempArray = []
tempArray = array[i].split(",");
dataArray.push(tempArray)
};
json = {};
var c = 1;
dataArray.forEach( (e1) =>{
isdate = true;
var tempjson = {};
e1.forEach( (e2) =>{
var key;
if(isdate ) {
key = 'date';
tempjson[key] = e2;
isdate = false;
}
else if(e2.includes("batteryCurrent")){
key = "batteryCurrent";
tempjson[key]= e2.split("batteryCurrent=")[1]
}
else{
var arr = e2.split("=");
key = arr[0].trim();
tempjson[key] = arr[1];
}
})
json[c] = tempjson;
c++
});
console.log(json)
Are you using node?
const fs = require('fs')
fs.readFile('log991/sensorData.log', 'utf8', (err, data) => {
console.log(data)
}
Use the readFile method of fs module.
var fs = require('fs')
fs.readFile('log991/sensorData.log', 'utf8', function(err, data) {
console.log(data)
});
Ok, i fix this with python
import json
a = open('log991/sensorData.log','r')
text = a.read()
text_as_list = text.split('\n')
keys = text_as_list[2].split()
result = []
for item in text.split('\n')[4:len(text_as_list)]:
temp_dict = {}
for i,j in zip(keys,item.split()):
if j.isdigit():
temp_dict[i] = int(j)
else:
temp_dict[i] = j
result.append(temp_dict)
print (json.dumps(result))

How to properly structure class in Node.js

I have a class called TileStreamer that I am currently defining as follows:
function TileStreamer {
};
This class has constants, which I define as follows:
// Tiles are 256 x 256 pixels
TileStreamer.prototype.TILE_SIZE = 256;
// Header size in bytes
TileStreamer.prototype.HEADER_SIZE = 28;
// Various table entry sizes in bytes
TileStreamer.prototype.RESOLUTION_ENTRY_SIZE = 12;
TileStreamer.prototype.TILE_COUNT_SIZE = 4;
TileStreamer.prototype.TILE_ENTRY_SIZE = 12;
// Offsets within header
TileStreamer.prototype.WIDTH_OFFSET = 3;
TileStreamer.prototype.HEIGHT_OFFSET = 4;
TileStreamer.prototype.NUM_TABLES_OFFSET = 7;
TileStreamer.prototype.UNPOPULATED_OFFSET = 12092;
There also other variables. These variables are important because they need to be accessible from other classes. They get their values within the methods of this class. This is what I am unsure of as far as structure. What I'm currently trying is:
TileStreamer.prototype.header;
TileStreamer.prototype.resolutionEntry;
TileStreamer.prototype.resolutionTable;
TileStreamer.prototype.filepath;
TileStreamer.prototype.s3;
TileStreamer.prototype.level;
TileStreamer.prototype.ncols;
TileStreamer.prototype.nrows;
TileStreamer.prototype.nlevels;
TileStreamer.prototype.toffset;
TileStreamer.prototype.tsize;
TileStreamer.prototype.modifiedTime;
TileStreamer.prototype.tile;
TileStreamer.prototype.host;
TileStreamer.prototype.bucket;
This class also has methods such as:
TileStreamer.prototype.Init = function(filepath, index, s3config){
var retval = false;
AWS.config.update({accessKeyId: s3config.access_key, secretAccessKey: s3config.secret_key});
var blc = new BlockLibraryConfigs();
var awsConfig = blc.awsConfig;
AWS.config.update({region: awsConfig.region});
var aws = new AWS.S3();
var params = {
Bucket: s3config.bucket,
Key: s3config.tile_directory + filepath,
Range: 'bytes=0-' + (this.HEADER_SIZE - 1)
};
aws.getObject(params, function(err, data){
if(err == null){
TileStreamer.modifiedTime = data.LastModified;
var header = bufferpack.unpack('<7I', data.Body);
TileStreamer.header = header;
TileStreamer.nlevels = header[TileStreamer.NUM_TABLES_OFFSET];
if(TileStreamer.nlevels == 5){
TileStreamer.level = 0;
TileStreamer.ncols = Math.ceil((header[TileStreamer.WIDTH_OFFSET] * 1.0) / TileStreamer.TILE_SIZE);
TileStreamer.nrows = Math.ceil((header[TileStreamer.HEIGHT_OFFSET] * 1.0) / TileStreamer.TILE_SIZE);
}
}
});
};
The method above should set some of the values of the variables, such as modifiedTime so that I can access it in another class such as:
TileStreamer = require('tilestreamer.js');
var ts = new TileStreamer();
ts.Init(parPath, index, config);
var last_modified = ts.modifiedTime;
Just put any public properties you want to initialise when the object is created, directly in the init function. Here's a small example...
function TileStreamer() {
};
TileStreamer.prototype.Init = function() {
this.modifiedTime = new Date();
};
var ts = new TileStreamer();
ts.Init();
console.log(ts);
jsfiddle example
https://jsfiddle.net/v6muohyk/
To get around the issue you're having with setting the object properties in a callback from an asynchronous function, just create a locally accessible variable to reference the object that you are creating at that time...
TileStreamer.prototype.Init = function() {
var thisTileStreamer = this;
asynchFunction(function(err, data) {
thisTileStreamer.modifiedTime = data.lastModified;
});
};
To take it one step further, if you need to execute some code after the init function has completed, then that will require waiting for the asynchronous function to complete, as well. For that, pass a further parameter to init, that is a function to be executed after all the work is done...
TileStreamer.prototype.Init = function(callback) {
var thisTileStreamer = this;
asynchFunction(function(err, data) {
thisTileStreamer.modifiedTime = data.lastModified;
callback();
});
};
var ts = new TileStreamer();
ts.Init(function() {
// put code here that needs to be executed *after* the init function has completed
alert(ts.modifiedTime);
});

NodeJS some modules not working

I'm making a game with socket.io and nodejs, and I'm making a module called rooms.js, this module require users.js module and fiveSocket.js module
but when I call Rooms.New from the main server file, it says that fiveSocket is undefined, same problem when Rooms.New calls a users.js function, I got TypeError: Cannot read property 'getSocketIDbyId' of undefined
rooms.js:
var mysql = require('../mysql/mysql.js');
var headers = require('./headers.js');
var users = require('./users.js');
var fiveSocket = require('./sockets.js');
var Rooms = {
Obj: {},
Room: function(data) {
var room = this;
this.name = data.name;
this.users = [];
this.floorCode = data.floor;
this.description = data.desc;
this.maxUsers = data.maxUsers;
this.owner = data.owner;
this.setTime = new Date().getTime();
this.dbID = data.dbID;
this.doorx = data.doorx;
this.doory = data.doory;
this.doordir = data.doordir;
},
New: function(socketID, roomID) {
var keys = Object.keys(Rooms.Obj).length;
var id = keys + 1;
var callback = function(row) {
fiveSocket.emitClient(socketID, headers.roomData, {
title: row.title,
desc: row.description,
mapStr: row.floorCode,
doorx: row.doorx,
doory: row.doory,
doordir: row.doordir
});
var uid = users.getIdBySocketID(socketID);
users.Obj[uid].curRoom = roomID;
var rid = Rooms.getIdByDbID(roomID);
Rooms.Obj[rid].users.push(uid);
}
if(Rooms.getIdByDbID(roomID) != false) {
var room = Rooms.getIdByDbID(roomID);
var row = { title: room.name, description: room.description, floorCode: room.foorCode, doorx: room.doorx, doory: room.doory, doordir: room.doordir };
callback(row);
} else {
mysql.Query('SELECT * FROM rooms WHERE id = ? LIMIT 1', roomID, function(rows) {
if(rows.length > 0) {
var row = rows[0];
Rooms.Obj[id] = new Rooms.Room({name: row.title, floorCode: row.floorCode, desc: row.description, maxUsers: row.maxUsers, owner: row.owner, dbID: row.id, doorx: row.doorx, doory: row.doory, doordir: row.doordir});
callback(row);
}
});
}
},
removeUser: function(DBroomID, userID) {
var rid = Rooms.getIdByDbID(DBroomID);
var room = Rooms.Obj[rid];
var index = room.indexOf(userID);
if (index > -1) array.splice(index, 1);
},
Listener: function(users) {
setInterval(function(){
for(var roomID in Rooms.Obj) {
var room = Rooms.Obj[roomID];
// send users coordinates
room.users.forEach(function(uid) {
var socketID = users.getSocketIDbyId(uid);
var data = Rooms.getUsersInRoomData(roomID);
fiveSocket.emitClient(socketID, headers.roomUsers, data);
});
// unload inactive rooms (no users after 10 seconds)
var activeUsers = room.users.length;
var timestamp = room.setTime;
var t = new Date(); t.setSeconds(t.getSeconds() + 10);
var time2 = t.getTime();
if(activeUsers <= 0 && timestamp < time2) {
Rooms.Remove(roomID);
}
}
}, 1);
},
getUsersInRoomData: function(roomID) {
var room = Rooms.Obj[roomID];
var obj = {};
room.users.forEach(function(uid) {
var user = users.Obj[uid];
obj[uid] = {
username: user.username,
position: user.position,
figure: user.figure
};
});
return obj;
},
Remove: function(id) {
delete Rooms.Obj[id];
},
getIdByDbID: function(dbID) {
var result = null;
for(var room in Rooms.Obj) {
var u = Rooms.Obj[room];
if(u.dbID == dbID) var result = room;
}
if(result == null) return false;
else return result;
},
getDbIDbyId: function(id) {
return Rooms.Obj[id].dbID;
}
}
Rooms.Listener();
module.exports = Rooms;
EDIT: (if it can be helpful)
When I console.log fiveSocket on the main file
When I console.log fiveSocket on the rooms.js file
EDIT2: When I've removed var users = require('./users.js'); from fiveSocket, when I console.log it in rooms.js it works, why ?
EDIT3: I still have the problem
If you need the others modules sources:
Users.JS: http://pastebin.com/Ynq9Qvi7
sockets.JS http://pastebin.com/wpmbKeAA
"Rooms" requires "Users" and vice versa, so you are trying to perform "circular dependency".
Quick search for node.js require circular dependencies gives a lot of stuff, for example :
"Circular Dependencies in modules can be tricky, and hard to debug in
node.js. If module A requires('B') before it has finished setting up
it's exports, and then module B requires('A'), it will get back an
empty object instead what A may have intended to export. It makes
logical sense that if the export of A wasn't setup, requiring it in B
results in an empty export object. All the same, it can be a pain to
debug, and not inherently obvious to developers used to having those
circular dependencies handled automatically. Fortunately, there are
rather simple approaches to resolving the issue."
or
How to deal with cyclic dependencies in Node.js

Categories