How do I create file with json inside? - json

I'm trying to create a new File() and write json to it but I Don't really understand how to.
I've looked at the documentation but I don't understand what BlobPart is.
When I tried this:
const file = new File(this.myFrom.getRawValue(), 'json');
I got error :
Failed to construct 'File': The object must have a callable ##iterator property.
I need to append the file to formData like this:
formData.append('file', file);

You're nearly right. You just need to
a) put the content inside an array, as per the documentation
b) set the content type through the options
This is the corrected version of the code:
const file = new File([JSON.stringify(this.configForm.getRawValue())], 'payapp_init_json.json', {type: 'application/json'});

Related

Getting JSON from HTTP Discord.Js

Im making a discord bot, and I have a URL here which has some raw json: link here and I want one of the values (hashrateString) to be put inside a embed like:
hashrateString: 1GH
is there a way to do that and if so how?
I never tried this with an external link but it should work the same way.
FIRST: write somewhere high up in your code this line
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('http://ric.pikapools.com/api/stats', 'utf8'));
After you can basically do whatever you want with your new object. There was no hashrateString: 1GH, but hashrateString: 4.68 GH should be accessible with data.algos.primesr.hashrateString (Output: 4.68 GH)
If it, for some weird reason, doesn't accept an URL, just try to copy&paste the text in a json file if possible, and use the path to it
I was able to get this to work by specifying a constant to be the JSON from the url using node-fetch
const ricp = await fetch('http://ric.pikapools.com/api/stats').then(response => response.json());
and find an object in the JSON using
message.channel.send(ricp.algos.primesr.hashrateString)

Read local JSON files when dynamically creating functional tests in Intern

I am creating functional tests dynamically using Intern v4 and dojo 1.7. To accomplish this I am assigning registerSuite to a variable and attaching each test to the Tests property in registerSuite:
var registerSuite = intern.getInterface('object').registerSuite;
var assert = intern.getPlugin('chai').assert;
// ...........a bunch more code .........
registerSuite.tests['test_name'] = function() {
// READ JSON FILE HERE
var JSON = 'filename.json';
// ....... a bunch more code ........
}
That part is working great. The challenge I am having is that I need to read information from a different JSON file for each test I am dynamically creating. I cannot seem to find a way to read a JSON file while the dojo javascript is running (I want to call it in the registerSuite.tests function where it says // READ JSON FILE HERE). I have tried dojo's xhr.get, node's fs, intern's this.remote.get, nothing seems to work.
I can get a static JSON file with define(['dojo/text!./generated_tests.json']) but this does not help me because there are an unknown number of JSON files with unknown filenames, so I don't have the information I would need to call them in the declare block.
Please let me know if my description is unclear. Any help would be greatly appreciated!
Since you're creating functional tests, they'll always run in Node, so you have access to the Node environment. That means you could do something like:
var registerSuite = intern.getPlugin('interface.object').registerSuite;
var assert = intern.getPlugin('chai').assert;
var tests = {};
tests['test_name'] = function () {
var JSON = require('filename.json');
// or require.nodeRequire('filename.json')
// or JSON.parse(require('fs').readFileSync('filename.json', {
// encoding: 'utf8'
// }))
}
registerSuite('my suite', tests);
Another thing to keep in mind is assigning values to registerSuite.tests won't (or shouldn't) actually do anything. You'll need to call registerSuite, passing it your suite name and tests object, to actually register tests.

Nodejs - trying to edit images' metadata with Exiftool

I am currently working on a NodeJS (Express) project to edit images' metadata with Exiftool.
To edit images' metadata with Exiftool, I've to create a JSON file containing all metadata to modify then execute the command :
exiftool -j=metadata.json pathToTheImage/image.jpg
The json file must look like that :
[{"SourceFile":"pathToTheImage/image.jpg","XMP-dc:Title":"Image's title"}]
Here's my code to do that :
const {exec} = require('child_process');
let fs = require('fs');
let uploadPath = "uploads";
let uploadName = "image.jpg";
...
app.post('/metadata/editor', (req, res) => {
let jsonToImport = [...];
fs.writeFileSync("metadata.json", JSON.stringify(jsonToImport));
exec('exiftool -j=metadata.json ' + uploadPath + '/' + uploadName, (error, stdout, stderr) => {
if (error) {
console.error(error);
return;
}
res.redirect('/metadata/checker/' + uploadName);
});
});
The problem is at the level of "writeFileSync/exec".
Independently these two lines work well, that's to say that if I've just the first line, the JSON file is well created. And if I've just the second ligne, image's metadata are well updated.
But when I execute this two lines together, the JSON file is well created but the exec line do "nothing" (or something that I can't determine).
This code uses synchronous functions, I've test it with asynchronous functions, this is the same behavior.
Currently, to do what I need, I must execute the code above to create the JSON file, then I must comment the writeFileSync line and I must reexecute the code to update image's metadata correctly.
It's really strange, I've try to read the JSON file content before the exec line but everything is ok. I've use asynchronous functions, with and without promise... there is nothing to do it doesn't work.
Thank you for your help.
I'll answer my own question:
The problem was that I use nodemon, however by default nodemon watches JSON files. But in my code I created a JSON file to use it right after. So, I created the JSON file correctly, nodemon sees it, and restarts the node server; the rest of the code does not run.
To fix this, I added an option to ignore the created files in my package.json:
"nodemonConfig": {
"ignore": [
"path/to/files/to/ingore/*"
]
}

Is there a way to send gulp.src(some data) instead of a glob?

I want to be able to edit JSON then send it through the gulp stream. I know there's gulp-json-edit but I want to understand how it's done and do it myself. In this case, to change the Basic authorization.
For example, something like this:
var data = JSON.parse(fs.readFileSync('./core-config.json'));
data.local.ENDPOINT.CORE.BASIC = "Basic Stuff";
gulp.src(data)
.pipe(somestuff)
.pipe(gulp.dest('./'));
However, this of course doesn't work because data isn't a glob. How can I then manipulate data in a way that I can then pass it to gulp.src()?
A while ago I wrote a module that can turn a regular object stream into a vinyl stream: vinylize. It's mostly useful for static site generation, but If I understand your question correctly it should be able to handle your use case as well.
Your example code using vinylize() would look like this:
var vinylize = require('vinylize');
var data = JSON.parse(fs.readFileSync('./core-config.json'));
data.local.ENDPOINT.CORE.BASIC = "Basic Stuff";
vinylize([data], {
path: 'core-config.json',
contents: JSON.stringify(data),
ignoreSourceProps: true,
})
.pipe(somestuff)
.pipe(gulp.dest('./'));

Local json object not working in Typahead Bloodhound

I am using Typeahead Bootstrap in a form field (with a WP framework).
I have a .json file stored in my root, which I can grab using prefetch:
prefetch: {
url: '
../json/test.json',
ttl: 1
}
menu works just fine. Now, let's say I dont want to use prefetch, but load the datum in a local json array.
I have the same json file that looks like:
[{"title":"Title 1","content":"Loopty loos"},{"title":"Title 2","content":"Diddly Bones"}]
If I load that directly into the new Bloodhound class:
local: [{"title":"Title 1","content":"Loopty loos"},{"title":"Title 2","content":"Diddly Bones"}]
again, works like a charm. However, if I try to load the same data in as a variable, rather than explicitly written:
jsonObject = [{"title":"Title 1","content":"Loopty loos"},{"title":"Title 2","content":"Diddly Bones"}]
var content = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.content);
},
local: jsonObject
...
It doesn't work. This seems like it's something simple and I am just completely missing it.
Full clarification, I am querying the wp database, and with that result set creating the json file and writing it to the test directory, then passing it to a .js file using wp_localize_script.
After declaring Bloodhound object, try to initialize the object.
var content = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.content);
},
local: jsonObject
...
})
content.initialize();