Expose result of method in Javascript - javascript

I have this method :
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
var KLVdata = KLV.parseKLVfile(file, options);
var packets = KLVdata.packets;
var nDropped = KLVdata.nDropped;
});
in a small Node app.
How to I get the variable packets outside this object?

It's actually quite simple. Define the variables outside the function, and set them inside. Like this:
// Define variables
var packets = null;
var nDropped = null;
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
var KLVdata = KLV.parseKLVfile(file, options);
packets = KLVdata.packets;
nDropped = KLVdata.nDropped;
});
function doSomething(){
// you can now use the variables anywhere
}
Also: make sure to only use the variables if they have been defined.
// Define variables
var packets = null;
var nDropped = null;
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
var KLVdata = KLV.parseKLVfile(file, options);
packets = KLVdata.packets;
nDropped = KLVdata.nDropped;
packetsReady(); // your callback function
});
function packetsReady(){
// should only be called once the packets are ready
processPackets(packets);
}

Simply pass it to a function
let packets;
let nDropped;
function processKLV(KLVdata){
packets = KLVdata.packets;
nDropped = KLVdata.nDropped;
}
// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
processKLV(KLV.parseKLVfile(file, options));
});

Related

Pass relative files into function using javascript file constructor

I'm trying to load in a relative file address into a function previously used by a file reader. On the site, I had a button that would let you pick local files to be loaded into a graphics renderer. I want to use a url to access these files relatively instead, but I can't figure out how to bind them to a file object. I have been using this mozilla documentation to try and figure it out.
Here is the code that was used originally:
// function that takes file input and renders the image
function readFiles(){
// Deal with file input
if (window.File && window.FileReader && window.FileList && window.Blob) {
var file1 = document.getElementById('fileinput').files[0];
var file2 = document.getElementById('fileinput').files[1];
// Call the file analyzer
fileAnalyzer( file1, file2 );
} else {
alert('The File APIs are not fully supported by your browser.');
}
}
Here is the code that I want to update:
// load cube button
var loadcube = document.getElementById('loadcube');
loadcube.onclick = function(evt) {
var file1 = new File([], "Object files/cube3.coor" );
var file2 = new File([], "Object files/cube3.poly" );
fileAnalyzer( file1, file2);
}
You can use the Fetch API to asynchronously fetch the resources, convert them to a Blob, and then construct a File like this:
function fetchAsFile(path) {
return fetch(path).then(function (response) {
return response.blob()
}).then(function (blob) {
return new File([blob], path)
})
}
var loadcube = document.getElementById('loadcube')
loadcube.addEventlistener('click', function () {
var p1 = fetchAsFile('Object files/cube3.coor')
var p2 = fetchAsFile('Object files/cube3.poly')
Promise.all([p1, p2]).then(function (files) {
fileAnalyzer(files[0], files[1])
})
})
Using ES2017 async / await, you can simplify the above like this:
async function fetchAsFile(path) {
let response = await fetch(path)
let blob = await response.blob()
return new File([blob], path)
}
var loadcube = document.getElementById('loadcube')
loadcube.addEventlistener('click', async function () {
let p1 = fetchAsFile('Object files/cube3.coor')
let p2 = fetchAsFile('Object files/cube3.poly')
let files = await Promise.all([p1, p2])
fileAnalyzer(files[0], files[1])
})

Why is this an unreachable code?

I'm calling the function getKeywords from another function and got an Unrecheable code detected section and don't understand why. Any help?
var env = require('dotenv').config();
var request = require('request')
var getKeywords = function(){
request.get('URI', //URI IS CORRECT IN MY CODE
function(err, httpResponse, body){
if(err){ //UNREACHABLE CODE DETECTED
console.error("request.post Error:", err);
return false;
} //UNREACHABLE CODE DETECTED
else{
console.log('Im here');
return JSON.parse(httpResponse.body).keywords;
}
});
}
module.export = getKeywords;
Here is the calling code.
var getKeywords = require('./getKeywords.js');
var keywords = new getKeywords();
var env = require('dotenv').config();
var difflib = require('difflib');
var postMention = require('./postMention.js');
var detection = function(obj, i){
var keyword = keywords[i];
var mentionObject = {
//some json
//postMention(mentionObject);
}
}
module.exports = detection;
Some tools have the ability to analyze every call to your function. It may be possible that all the places in your code that call the function you never set err parameter to true.

Nodejs non-blocking and Event Emitter. Refresh URL

fist of all im not shure if the following is a non-blocking problem?
im getting started with https://github.com/sahat/hackathon-starter
currently i try to read all files out of a folder and later process all files...
i used EventEmitter to kind of manage the workflow.
i want to clear all arrays if the URL is refeshed or loaded new, but somehow if i reaload the URL there seems to be something inside the arrays which cases multiple outputs of the same data?
at the moment i just would be happy to have a correct console.log output.
/**
* GET /
* Home page.
*/
var fs = require('fs');
//XML
var jsxml = require("node-jsxml");
var Namespace = jsxml.Namespace,
QName = jsxml.QName,
XML = jsxml.XML,
XMLList = jsxml.XMLList;
//EventEmitter
var EventEmitter=require('events').EventEmitter;
var dateinamenEE=new EventEmitter();
var dateiinhaltEE=new EventEmitter();
var dateinamen = [];
var dateiinhalt = [];
exports.index = function(req, res) {
fs.readdir('./data', function (err, files) {
if (!err) {
files.forEach(function(value) {
dateinamen.push(value);
});
dateinamenEE.emit('dateinamen_ready');
} else {
throw err;
}
});
dateinamenEE.on('dateinamen_ready',function(){
dateinamen.forEach(function(value) {
var buf = fs.readFileSync('./data/'+value, "utf8");
var xml = new XML(buf);
var list = xml.descendants("suggestion");
var ergebnis = "";
var basiswort = "";
var buchstabe = "";
var obj = null;
list.each(function(item, index){
ergebnis = item.attribute('data').toString()
//basiswort = value.replace("%2B", " ");
//basiswort = basiswort.replace(".xml", "");
//var pieces = buchstabe.split(" ");
obj = {k: basiswort, b: buchstabe, e: ergebnis};
dateiinhalt.push(obj);
});
});
dateiinhaltEE.emit('dateiinhalt_ready');
});
dateiinhaltEE.on('dateiinhalt_ready',function(){
//console.log(dateiinhalt);
console.log("dateinamen:" + dateinamen.length);
console.log("dateiinhalt:" + dateiinhalt.length);
});
res.render('home', {
title: 'Home'
});
};
If if log the length of the 2 arrays the output on the second reload shows. First time loading the url:
Express server listening on port 3000 in development mode
dateinamen:2
dateiinhalt:20
Second time / refreshing the url:
GET / 200 898.198 ms - -
GET /fonts/fontawesome-webfont.woff2?v=4.3.0 304 12.991 ms - -
GET /favicon.ico 200 4.516 ms - -
dateinamen:4
dateiinhalt:60
dateinamen:4
dateiinhalt:60
dateinamen:4
dateiinhalt:100
dateinamen:4
dateiinhalt:100
GET / 200 139.259 ms - -
What causes the code to extend the arrays while reloading the page?
The non-blocking problem is due do your for(...) loops.
Changing them by : array.forEach(function(elem, index){});
EDIT
The arrays should be initialized inside the index function :
exports.index = function(req, res) {
var dateinamen = [];
var dateiinhalt = [];
...
Also, I'm not sure you need the use of EventEmitter.
Something like
`
fs.readdir('./data', function (err, files) {
if (!err) {
files.forEach(function(file){
var buf = fs.readFileSync('./data/'+file, "utf8");
var xml = new XML(buf);
var list = xml.descendants("suggestion");
var ergebnis = null;
var obj = null;
list.each(function(item, index){
ergebnis = item.attribute('data').toString();
obj = {k: file, v: ergebnis};
dateiinhalt.push(obj);
});
});
console.log(dateiinhalt);
} else {
throw err;
}
});
`
could do the job no?
(I wanted to say this as a comment, but I'm still missing reputation)

Load multiple JSON files in pure JavaScript

I am new to JavaScript. I have already understood how to create an object from a JSON-file with JSON.Parse() and now I need to load multiple local JSONs into an array. I've been googling my problem for a while, but everything that I found was related to single JSON files.
Is there any way to do this in pure JavaScript without any libraries like jQuery and etc.?
P.S.: There is no need to work with web-server or else, the code is running locally.
To do this, you need to first get the actual files. Then, you should parse them.
// we need a function to load files
// done is a "callback" function
// so you call it once you're finished and pass whatever you want
// in this case, we're passing the `responseText` of the XML request
var loadFile = function (filePath, done) {
var xhr = new XMLHTTPRequest();
xhr.onload = function () { return done(this.responseText) }
xhr.open("GET", filePath, true);
xhr.send();
}
// paths to all of your files
var myFiles = [ "file1", "file2", "file3" ];
// where you want to store the data
var jsonData = [];
// loop through each file
myFiles.forEach(function (file, i) {
// and call loadFile
// note how a function is passed as the second parameter
// that's the callback function
loadFile(file, function (responseText) {
// we set jsonData[i] to the parse data since the requests
// will not necessarily come in order
// so we can't use JSONdata.push(JSON.parse(responseText));
// if the order doesn't matter, you can use push
jsonData[i] = JSON.parse(responseText);
// or you could choose not to store it in an array.
// whatever you decide to do with it, it is available as
// responseText within this scope (unparsed!)
}
})
If you can't make an XML Request, you can also use a file reader object:
var loadLocalFile = function (filePath, done) {
var fr = new FileReader();
fr.onload = function () { return done(this.result); }
fr.readAsText(filePath);
}
You can do something like this:
var file1 = JSON.parse(file1);
var file2 = JSON.parse(file2);
var file3 = JSON.parse(file3);
var myFileArray = [file1, file2, file3];
// Do other stuff
// ....
// Add another file to the array
var file4 = JSON.parse(file4);
myFileArray.push(file4);
If you already have an array of un-parsed files you could do this:
var myFileArray = [];
for(var i=0; i<unparsedFileArray.length; i++){
myFileArray.push(JON.parse(unparsedFileArray[i]));
}

Why is db.transaction not working with indexeddb?

I am new at using inxededdb and am trying to get data out of a store. The store contains data, but for some reason the code stops after trying to set the var tx. If I am missing anything please let me know. Here is the function with which I am trying to get the book:
function getBook(){
var tx = db.transaction("book", "readonly");
var store = tx.objectStore("book");
var index = store.index("by_getid");
var request = index.get("<?php echo $_GET['book'] ?>");
request.onsuccess = function() {
var matching = request.result;
if (matching !== undefined) {
document.getElementById("text-container").innerHTML = matching.text;
} else {
alert('no match');
report(null);
}
};
}
Solved Version:
function getBook(){
var db;
var request = indexedDB.open("library", 1);
request.onsuccess = function (evt) {
db = request.result;
var transaction = db.transaction(["book"]);
var objectStore = transaction.objectStore("book");
var requesttrans = objectStore.get(<?php echo $_GET['book'] ?>);
requesttrans.onerror = function(event) {
};
requesttrans.onsuccess = function(event) {
alert(requesttrans.result.text);
};
};
}
The problem is probably your db variable. You are probably accessing a closed or null instance of a connection object.
Try instead to create the db connection right inside the function. Do NOT use a global db variable.
index.get yields primary key. You have to get record value using the resulting primary key.
I has problem with transaction, it's return error db.transaction is not a function or return undefined.
You will try like this, it's working for me:
const table = transaction.objectStore('list');
const query = table.getAll();
query.onsuccess = () => {
const list = query?.result;
console.log(list);
};

Categories

Resources