Using elasticsearch.js - javascript

I've run elasticsearch.bat and queried this in browser with localhost:9200. JSON object returned as follows, so all ok so far.
{
"status" : 200,
"name" : "hwils_01_dev",
"cluster_name" : "elasticsearch_hwils_dev",
"version" : {
"number" : "1.7.2",
"build_hash" : "e43676b1385b8125d647f593f7202acbd816e8ec",
"build_timestamp" : "2015-09-14T09:49:53Z",
"build_snapshot" : false,
"lucene_version" : "4.10.4"
},
"tagline" : "You Know, for Search"
}
I've downloaded and linked via tag to my index.html the elasticsearch.js
<script src="elasticsearch-js/elasticsearch.js"></script>
(incidentally there's more than 1 .js in the download - do I need to link them all?)
I've then run added to another tag the code
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
and output this to console - JSON object returned so again, presumably all ok up to this point.
If I then run
client.ping({
requestTimeout: 30000,
// undocumented params are appended to the query string
hello: 'elasticsearch'
}, function (error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
I get the error message returned. And I don't know why.
Incidentally
var elasticsearch = require('elasticsearch');
returns "Uncaught reference error: require is not defined" which would suggest I'm missing at least one other .js file with that function?

Since you're in a browser, you need to use a browser build (at the moment Angular or jQuery are available).
So let's say you're going the jQuery way, your <script> should look like this:
<script src="elasticsearch-js/elasticsearch.jquery.min.js"></script>
And then you can create your client like this:
var client = new $.es.Client({
hosts: 'localhost:9200',
log: 'trace'
});

The require statement is a NodeJS only function. You need to download and reference the browser build of ES in your HTMl file as Val mentioned.

Related

Using pouchdb-load with a local file

I’m using react to build a .html page facilitating the access to a complicated local file system for the place I work at. This needs to be editable by anyone. I’ve decided to use pouchdb to handle a database which is storing all my buttons with the link attached to them.
This needs to be deployed on multiple computers. The command npm run build works perfectly fine, however, the button database is not shared between the computers, since the pouchdb database is stored in the localstorage.
So I came up with a way to dump the pouch database in a .json file.
The dumping procedure works fine, however when I try to get the data from the .json file using pouchdb-load plugin, I get a CORS error.
this.db.load('file:///./tracker.json').then(function () {
// done loading!
console.log(this.db)
}).catch(function (err) {
// HTTP error or something like that
console.log(err)
});
I get an undefined object which is related to a CORS error:
Access to XMLHttpRequest at 'file:///tracker.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
message: undefined
name: "unknown"
status: 0
When I omit the 'file:///' behind the file path i get the following :
yntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at index.js:16
at Array.forEach (<anonymous>)
at parseDump (index.js:12)
at loadString (index.js:32)
at index.js:87
at onSuccess (index-browser.js:288)
at index-browser.js:330
at XMLHttpRequest.xhr.onreadystatechange (index-browser.js:198)
The project needs to be build as local .html file since we need to be able open links to files.
What could I do to make pouchdb-load work in such a configuration ?
I'm quite lost at the moment, so any help is appreciated ! What am I doing wrong? Is there any simple trick to open files from the file system without any action from the user ? Is there any other way that I could store a copy of my pouchdb database on the file system ? And if so, how could I retrieve it?
Indeed the dreaded CORS error, what a pain! Of course CORS is most necessary, without which local file exploitations would be rife.
The obvious solution is to serve the file over HTTP, either locally - nodejs comes to mind - or serve from a remote server. Here I offer a workaround which is suitable for this use case, maybe not for others.
This solution hinges on two facts: The browser allows the loading of local script files relative to the local document, and pouchdb-load supports loading a database from a string.
For the benefit of those starting from scratch, let's start with creating a dump of a CouchDB database. I used curl and jq1,2 to make a dump suitable for import
curl -X GET "http://localhost:5984/sratch/_all_docs?include_docs=true"
| jq-win64 "{"""docs""": [.rows[].doc]}" > db.js
(Above from a VSCode terminal on windows - hence the triple quotes 😒)
OK so now we have an .js file, which for me looks like this
{
docs: [
{
_id: "a369bc7329751c1642476e752b000f8d",
_rev: "1-6a0a8c1a35c6bb106fc3c53cdc99c034",
id: "4567",
user: "test2",
address: {
city: "New York",
},
},
{
_id: "a369bc7329751c1642476e752b00290e",
_rev: "1-29508c896c6c773775c2c46f67714aad",
id: "4568",
user: "test2",
info: {
city: "Atlanta",
},
},
// etc....
Of course this is a JSON file with a .js extension. Why? Let's change the raw JSON into a variable with a quick edit of the dump file:
let CANNED_LOCAL_DB = {
docs: [
{
_id: "a369bc7329751c1642476e752b000f8d",
// etc....
Excellent, the database is now a JavaScript object. Let's load it.
Bare bones HTML:
<html>
<body>
<script src="./db.js"></script>
<script src="./scripts/pouchdb.js"></script>
<script src="./scripts/pouchdb.memory.js"></script>
<script src="./scripts/pouchdb.load.js"></script>
<script src="./scripts/index.js"></script>
</body>
</html>
Here's the index.js code, proving the concept.
// "local" db
const ldb = new PouchDB("ldb", { adapter: "memory" });
// load the database from the object, stringified
ldb.load(JSON.stringify(CANNED_LOCAL_DB))
.then(() => {
CANNED_LOCAL_DB = undefined;
return ldb.info();
})
.then((info) => {
console.log(JSON.stringify(info, undefined, 3));
})
.catch((err) => {
console.log(err.toString());
});
The canned db object is set to undefined after load - no reason to let it linger in memory.
Do understand db.js is loaded synchronously, which may have an ugly impact with massive canned db's. This may be worked around, but is beyond the scope of this answer.
1 CouchDB dump to file and load from file
2 jq, a lightweight and flexible command-line JSON processor

Azure Functions - Value cannot be null. (Parameter 'connectionString')

I was trying to setup simple Azure Function to read a XML stream and sync it back to the database. My plan was to use a Time Trigger to execute the function once per day.
Howerver, things are not looking great. I'm getting the following error, even if I don't use a database:
[Error] Executed 'Functions.<func-name>' (Failed, Id=<func-id>, Duration=1ms)Value cannot be null. (Parameter 'connectionString')
I'm currently trying to execute the following function:
module.exports = async function(context, req) {
context.res = {
body: "Success!"
};
};
Same result. I can't run it.
I've added a Connection String to the Configuration -> Connection Strings (I thought that I've missed that, based on the message).
My functions.json file looks like:
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 * * * *"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
I've also tried running a C# function - same result.
So, what have I missed?
Logging from Microsoft to it's finest.
AzureWebJobsStorage App Setting was missing.
Solution:
Create Storage account (or use existing one)
Go to your Function App's Configuration
Add AzureWebJobsStorage with a connection string to your Storage account (can be found at Storage Account Overview -> Access Keys)
In my case the error was Microsoft.Extensions.Configuration.AzureAppConfiguration value cannot be null: parameter (connectionString)
This happened because I has installed Microsoft.Extensions.Configuration.AzureAppConfiguration in my Function to DI the configuration into my main function. The Startup.cs line string cs = Environment.GetEnvironmentVariable("MyDifferentConnectionString"); was not able to find an environment variable for MyDifferentConnectionString, so this needed to be added to the Function config.
Go to App Configuration (or create one)
Access Keys (under Settings)
Copy Connection String
Go to your Function
Configuration (under Settings)
Add a new Application Settings with the name of your environment variable and paste the value
Save and restart your Function

Get StdOut from RunCommand using Azure VM Javascript SDK

I'm using the Azure VM Javascript SDK in my Node.js webApp. I'm trying to use the RunCommand Function to run a custom script on my Azure virtual machines.
The problem I'm having is with obtaining the response from running the command which should contain the StdOut and StdErr strings.
If I run the command from the Azure CLI, Like the following:
az vm run-command invoke -g 'myResource' -n 'myVm' --command-id RunPowerShellScript --scripts 'Get-ChildItem -Name'
Then I am able to receive the response, e.g. (notice in the 'message' section there is a listing of the files returned from 'Get-ChildItem')
{
"value": [
{
"code": "ComponentStatus/StdOut/succeeded",
"displayStatus": "Provisioning succeeded",
"level": "Info",
"message": "myTxtFile.txt\nscript12.ps1\nscript13.ps1\nscript14.ps1\nscript15.ps1\nscript16.ps1\nscript17.ps1\nscript18.ps1\nscript19.ps1\nscript20.ps1\nscript21.ps1\nscript22.ps1\nscript23.ps1\nscript24.ps1\nscript25.ps1\nscript26.ps1",
"time": null
},
{
"code": "ComponentStatus/StdErr/succeeded",
"displayStatus": "Provisioning succeeded",
"level": "Info",
"message": "",
"time": null
}
]
}
However, when I run this code from the javascript SDK I don't get any thing returned. Here is the code:
let usr = ...;
let pas = ...;
let subscriptionId = ...;
let client = null;
msRestAzure.loginWithUsernamePassword(usr, pas, function(err, credentials) {
if (err) return console.log(err);
client = new azureArmCompute.ComputeManagementClient(credentials, subscriptionId);
let param = {
commandId: 'RunPowerShellScript',
script: [
'echo $null >> myTxtFile.txt\n' +
'Get-ChildItem -Name\n'
]
};
client.virtualMachines.runCommand('myResource', 'myVm', param, function (err, result) {
console.log(err);
console.log(result);
})
});
and here is what is printed to the console:
null
{}
I know that the script is actually running because I tried, and was successfully able, to create a text file (myTxtFile.txt).
Anyone have any clues as to why I'm not getting anything in the result object?
Edit 1 (in response to #Itay):
Looking at the source, the callback is supposed to be a "ServiceCallback" of type "RunCommandResult". Here are the three function declarations for RunCommand.
Here's the declaration for the ServiceCallback interface.
So in my callback I was expecting there to be four returns "err" and "result" and "request" and "response" (I'm obviously leaving off the latter two). In my example I'm printing the error and result objects to the console, but the result object doesn't have anything in it...
I think the signature for the callback you defined is not as described by the documentation.
Looking at runCommand(string, string, RunCommandInput, ServiceCallback< RunCommandResult >), it seems that the callback should be accepting a RunCommandResult interface, which in turn, contains a property called Value which is an array of InstanceViewStatus interface instances that might hold the information you are looking for.
Hope it helps!

How do I fix indentation/alignment in my pull request in Bitbucket?

I have written a small piece of JavaScript code (not allowed to share code). The code is aligned perfectly in text editor (Sublime) but in the pull request it is distorted. I tried to solve this but failed.
I tried to save each line but the result in pull request in still same. In SourceTree the indentation is correct before I push the code to the repository but after the push is successful the alignment dies.
Please forgive if this is a stupid question to ask to the developer community.
Sample code
$(document).ready(function()
{
var validate = $("#formId").validate(
{
debug : true,
rules : {
Name : {
required : true
}
},
messages : {
Name: {
required : "Name is required"
}
},
onfocusout : false,
invalildHandler : function (form, validator)
{
var errors = validator.numberofInvalids();
if(errors)
{
validator.errorList[0].element.focus();
}
}
});
})
So this is how it is actually supposed to be (above code) but in the pull request it comes something like this
$(document).ready(function()
{
var validate = $("#formId").validate(
{
debug : true,
rules : {
Name : {
required : true
}
},
messages : {
Name : {
required : "Name is required"
}
},
onfocusout : false,
invalildHandler : function (form, validator)
{
var errors = validator.numberofInvalids();
if(errors)
{
validator.errorList[0].element.focus();
}
}
});
})
I wonder if it'd figure out the problem, but hope you'd make a try anyway.
Download the conflicted target .js file from Bitbucket. (It doesn't matter whether it's a js file or not.) It's easy to make a file download if you open it as a raw status.
Replace your local original file with that one. It means you're going to get rid of confliction from your local side.
Make a commit to remote Bitbucket repo by git push -u origin [your_branch]. If your branch is not the master one, make a PR(pull request) and update your local branches syncing with remote ones.
Now you can recover your own indentation/alignment style on your favorite editor as you wish! (local edit)
Finally, make a commit to Bitbucket again.
To make a long story short, you can apply your own indentation after Git conflicts would get fixed.
Thanks.

Code:1000 Can't write or create a file in my app using ionic-native/file ionic 2

I am now working on a hybrid app working on localization, the logic is that the user will have as an example 3 options to choose languages, I am having a node.js server on bluemix that deals with cloudant-nosql db to get on point i compare my local json file "rev" value with the other one on server if they are different then I have to overwrite the local file with the updated one, I have this result but I can't write this data to the local file, I am now working with cordova and ionic 2 ,
public GetRevFromNode(SelectedLanguage,JsonDataLocal)
{
JsonDataLocal.subscribe(val=>{ this.LocJson=val; })
this.http.get('https://*********/retriev?ID=\"'+SelectedLanguage+"\"").subscribe( result=>
{
if(this.LocJson['_rev']==result.json().value)
{
console.log("The Local Json is Updated to the latest");
return ;
}
{
console.log("Updating Json File for "+SelectedLanguage+".json .......");
var ob=this.file.readAsText(this.file.applicationDirectory+'www/assets/i18n',"ar.json");
ob.then(function(val){
console.log("ar JSON = "+val);
});
this.file.createFile('file:///android_asset/www',"ess.json",true).catch(val=>{
console.log("Can't create because = "+JSON.stringify(val));
});
this.file.writeFile('file:///android_asset/www/',"index.html","\"value\":\"Please\"",{replace:true , append:false} ).catch(val=>{
console.log("Can't write because ="+JSON.stringify(val));
console.log("Updating Done ...")
}
} );
}
Tried to use this.file.appDirectory error also tried to make it implicitly like here
The error is
uncaught promise [object Object]
by using stringify {Code:1000}
but I can read normally and check if file exists normally the problem is with creating and writing
See https://github.com/apache/cordova-plugin-file#android-file-system-layout
The problem is that I can't write in the applicationDirectory path as this path read-only.

Categories