Vert.x how to call a file in module - groovy

I have a module like this structure:
module_root/
mod.json
filestore/myfile
com/my/www/my.groovy(Compiled to my.class)
I want to call filestore/myfile in my.groovy. I tried many methods to access the file, but I failed.
First, I try to use relative path. Both ../../../filestore/myfile and filestore/myfile failed. No such file or directory.
new FileInputStream('../../../filestore/myfile').withStream {
// ...
}
Then I try to use absolute path, I don't know how to get the module's absolute path. I try to get the my.groovy path use this code:
scriptFile = getClass().protectionDomain.codeSource.location.path
But when I exec vertx runzip mymodule.zip, I get an exception:
java.lang.NullPointerException: Cannot get property 'location' on null object
How to do this?

for me this works..please let me know if works for you:
this is js, I don't know groovy but I suppose than must be similar
var CURRENT-DIRECTORY = new java.io.File("").getAbsolutePath()
then you can use string concatenation
CURRENT-DIRECTORY+"/filestore/myfile/mysuperFile.groovy" <--notice the /
remember than the response is a buffer, maybe you must be convert this to string
return response.toString()
good luck

Related

Node.js name too long, scandir

I have a folder structure which starts at my project
Note that user.hash and user are MD5 hash
root/data/${user.hash}/
Now, what i need to do is read the files in side that directory using:
var companies = fs.readdirSync(`../data/${user}/`);
I also tried
var BASE_FOLDER = path.resolve(__dirname, "..");
var companies = fs.readdirSync(`${BASE_FOLDER}/data/${user}/`);
And in both cases i get the following error:
UnhandledPromiseRejectionWarning: Error: ENAMETOOLONG: name too long, scandir '../data/callback => {
AND HERE MY CODE FOLLOWS
So far what i understood is that the file path string is too long ? How can we workaround an error like this if we are limited to that certain path... ?
It looks like user is a function for some reason (depends on where it comes from / where you initialize it) and what you see in the error message ../data/callback => { ... is the stringified version of that function.
I would double check that user is really just a string identifier for the user. Based on your first example, shouldn't you use user.hash?

Unable to use variables in fs functions when using brfs

I use browserify in order to be able to use require. To use fs functions with browserify i need to transform it with brfs but as far as I understood this results in only being able to input static strings as parameters inside my fs function. I want to be able to use variables for this.
I want to search for xml files in a specific directory and read them. Either by searching via text field or showing all of their data at once. In order to do this I need fs and browserify in order to require it.
const FS = require('fs')
function lookForRoom() {
let files = getFileNames()
findSearchedRoom(files)
}
function getFileNames() {
return FS.readdirSync('../data/')
}
function findSearchedRoom(files) {
const SEARCH_FIELD_ID = 'room'
let searchText = document.getElementById(SEARCH_FIELD_ID).value
files.forEach((file) => {
const SEARCHTEXT_FOUND = file.includes(searchText.toLowerCase())
if (SEARCHTEXT_FOUND) loadXML(file)
})
}
function loadXML(file) {
const XML2JS = require('xml2js')
let parser = new XML2JS.Parser()
let data = FS.readFile('../data/' + file)
console.dir(data);
}
module.exports = { lookForRoom: lookForRoom }
I want to be able to read contents out of a directory containing xml files.
Current status is that I can only do so when I provide a constant string to the fs function
The brfs README contains this gotcha:
Since brfs evaluates your source code statically, you can't use dynamic expressions that need to be evaluated at run time.
So, basically, you can't use brfs in the way you were hoping.
I want to be able to read contents out of a directory containing xml files
If by "a directory" you mean "any random directory, the name of which is determined by some form input", then that's not going to work. Browsers don't have direct access to directory contents, either locally or on a server.
You're not saying where that directory exists. If it's local (on the machine the browser is running on): I don't think there are standardized API's to do that, at all.
If it's on the server, then you need to implement an HTTP server that will accept a directory-/filename from some clientside code, and retrieve the file contents that way.

How can I read json values from a file?

So basically I have these json values in my config.json file, but how can I read them from a .txt file, for example:
{"prefix": $}
This would set a variable configPrefix to $. Any help?
You can use require() to read and parse your JSON file in one step:
let configPrefix = require("./config.json").prefix;
Or, if you wanted to get multiple values from that config:
const configData = require("./config.json");
let configPrefix = configData.prefix;
If your data is not actually JSON formatted, then you have to read the file yourself with something like fs.readFile() or fs.readFileSync() and then parse it yourself according to whatever formatting rules you have for the file.
If you are going to be reading this file just as the start of the program then go ahead and use require or import if you have babel. just a tip, suround the require with a try catch block to handle possible errors.
let config
try {
config = require('path.to.file.json')
} catch (error) {
// handle error
config = {}
}
If you will be changing this file externally and you feel the need to source it then apart from reading it at the start you will need a function that uses fs.readFile. consider doing it like this and not with readFileAsync unless you need to block the program until you are done reading the config file.
After all of that you can do const configPrefix = config.prefix which will have the value '$'.

How to pass a global variable before it gets rewritten to a fs.readFile in nodejs

Update: I think I found the answer to a similar problem in here: NodeJS readFile() retrieve filename
the point is that loops and have several call in http are actually kind of the same problem. The smartest solution may be to use ForEach instead of For
Hi I have the following code:
path = foo;
fs.readFile(path, function(err, data){
do_something_with_data(data);
do_something_with_path(path);
});
The problem is that the value of foo & path is overwritten with each single http request. So when the function do_something_with_path(path); is executed, the value of path is not the same as the one that was send as argument on fs.readFile(path ..
Is there anyway to use within fs.readFile the path value that was used instead of the last one?
Don't use a global variable. Instead, make a in-function variable. So whenever the function is called, a variable will be created which has something to do with this file.
Another try: use
var path = foo;
You can create a global variable in another module then reference this from the file you are using readFile.
Create a settings.js file in your project root:
module.exports = {
path: foo // Your variable
}
Inside your other js file where fs.readFile is being used.
var settings = require('../settings'); // Relative path to your settings file.
Then you can use settings.path as your global variable.
var settings = require('../settings');
path = foo;
fs.readFile(path, function(err, data){
do_something_with_data(data);
do_something_with_path(settings.path);
});
Use global keyword to store value of a variable globally
like following
global.path = foo;
It will store value globally.
Thanks

Error "Unable to get property 'normalize' of undefined or null reference" in require.js with text.js

I'm making my first attempt at using the text.js plugin (v2.0.12) for require.js (v2.1.15). I've had require working well up to this point, however, when I attempt to resolve a text dependency, I get two errors. The first error is Unable to get property 'normalize' of undefined or null reference [require.js, Line: 955] then, after the allotted time, I'll get a timeout error for the html file I'm attempting to load. The focus of this cry for help is the former error.
One curious observation I've noticed is that if I resolve the text module without declaring a file, there is no error. However, when I add the file path e.g. text!path/file, the error is triggered.
Additionally, I noticed that the load timeout error references the text module with _unnormalized2 appended. Not sure if that's to be expected but I thought is odd. Any help would be greatly appreciated!
Here's the block of code which errors:
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) { // error occurs here (line 955)
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
// ...
}
Ok, it turns out to have been a self-sabotage! I was creating a shortcut definition for the text module for which I left out the factory method. So, instead of
define('text', ['Scripts/text'], function(text) { return text; });
I had:
define('text', ['Scripts/text']);
Nothing to do with text.js whatsoever.

Resources