I was developing a Windows 10 app with HTML5 and Javascript.
In one part of the code I need to get data from a json file which is located in the project folder. I tried below , but it doesnt seems to be working.
try
{
$.getJSON('../js/towards_beach.json', function (data)
{
document.getElementById("Result").innerText = "We are working on it";
});
}
catch(err)
{
document.getElementById("Result").innerText = err;
}
Does any one have a clue how I can do it?
Do I need to register this function in winjs?
If you use jquery to do the request the right way is :
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
}).done(function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
}).always(function() {
console.log( "complete" );
});
doc is here http://api.jquery.com/jquery.getjson/
If you use WinJS.xhr
WinJS.xhr({url:"example.json"}).done(
function completed(request) {
console.log( "success" );
},
function error(request) {
console.log( "error" );
},
function progress(request) {
console.log( "progress" );
});
doc is here https://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx
the following code will help you to read JSON file
var url = new Windows.Foundation.Uri("ms-appx:///data/data.json");
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function (file){
Windows.Storage.FileIO.readTextAsync(file).then(function (text) {
var parsedObject = JSON.parse(text);
// do something with object
});
});
Put this code in a function wherever you want :) happy coding
Related
I have succesfully implemented the nativescript-audio plugin on android. I am using plain JS in my project. When i run it on ios i get the following error.
NSURLErrorDomain Code= -1002 "unsupported url".
I get this error with most of the examples that i found on the web (including the following , which works perfectly on android).
var ns_audio = require("nativescript-audio");
var player = new ns_audio.TNSPlayer();
var playerOptions = {
audioFile: "http://www.noiseaddicts.com/samples_1w72b820/2514.mp3",
loop: false,
completeCallback: function () {
console.log('completePlayer')
},
errorCallback: function (errorObject) {
console.log(JSON.stringify(errorObject));
},
infoCallback: function (args) {
console.log(JSON.stringify(args));
}
};
player.playFromUrl(playerOptions)
.then(function (res) {
console.log(res);
})
.catch(function () {
console.log("didn't work...");
})
It looks like recording works (no errors, and the correct responses, although i cannot test if the file has been correctly created...) But playback gives this error. Any idea ?
I have created a plain JS playground for you. I have tested the mp3 URL that you have provided in the the post and that works fine on ios.
Have a play with that and see if you are missing something. Here is
function pageLoaded(args) {
var page = args.object;
const player = new audio.TNSPlayer();
const playerOptions = {
audioFile: 'http://www.noiseaddicts.com/samples_1w72b820/2514.mp3',
loop: false,
completeCallback: function () {
console.log('finished playing');
},
errorCallback: function (errorObject) {
console.log(JSON.stringify(errorObject));
},
infoCallback: function (args) {
console.log(JSON.stringify(args));
}
};
player
.playFromUrl(playerOptions)
.then(function (res) {
console.log(res);
})
.catch(function (err) {
console.log('something went wrong...', err);
});
page.bindingContext = homeViewModel;
}
Recording and Playback with the nativescript-audio plugin (for iOS) are both working now!. My first problem was that i needed to record to .caf (not .mp3) so i used
if(isAndroid)
{
extention = ".mp3";
}
else
{
extention = ".caf";
}
before i record the audio file....
Also i ran in a stupid oversight which is easy to miss....
i created my code from the above mentioned example, but because i play the sound that is recorded to a .caf file. i needed to use playFromFile and not playFromUrl as the example uses.
( thats what caused the error : NSURLErrorDomain Code= -1002 "unsupported url".)
player
.playFromFile(playerOptions)
.then(function (res) {
hopefully this point of attention can save someone a headache !
I am trying to write a nightwatch test script with conditions in the test script. My code so far
module.exports = {
tags: ['getting-started'],
set_url: function (browser) {
browser.url('http://www.google.com');
browser.pause(5000);
browser.assert.title('Google');
if (browser.expect.element('#main').to.be.present) {
browser.pause(5000);
browser.setValue('input[type=text]', ['Night Watcher', browser.Keys.ENTER]);
browser.pause(5000);
if(browser.assert.containsText('#main', 'The Night Watch')){
console.log('search has the right result'); // for example
}else{
console.log('No result found');
}
}
browser.end();
}
}
But the browser.expect.element('#main').to.be.present and browser.assert.containsText('#main', 'The Night Watch') returns an object and is not actually the result I am interested with.
But the browser.expect.element('#main').to.be.present and browser.assert.containsText('#main', 'The Night Watch') returns an object and is not actually the result I am interested with.
I am using page objects...If you don't use page objects then just say browser.elements. The following solution worked for me
.waitForElementPresent('#main', 1000)
.api.elements('css selector','input[type=text]',function(result){
console.log("123");
if(result.value) {
console.log("======================================");
this.setValue('input[type=text]', ['Night Watcher', this.Keys.ENTER]);
}
})
.waitForElementPresent('#main', 1000, function(res) {
if(res.value) {
console.log('search has the right result');
}else{
console.log('No result found');
}
})
Following was the output that I got from the code.. Hope this helps you.. The code could be more optimized though.
Heading
This is very basic :
module.exports = {
tags: ['getting-started'],
set_url: function(browser) {
browser.url('http://www.google.com')
.pause(5000)
.assert.title('Google')
.waitForElementPresent('#main', 3000, function(result) {
if (result.value === true) { // '#main is present
this
.setValue('input[type=text)', 'Night Watcher')
.click('#search') //instead of enter, you can click search button
.getText("#main", function(result) {
console.log(result.value);
// You can continue here
});
}
})
.end();
}
};
I've got a node.js-based webserver running at home and i'm trying to implement a login form.
So basically I need to access POSTed data (login/password). I found this :
How do you extract POST data in Node.js?
(req.on('data'...) & req.on('end'...))
But i need to do this asynchronously, can someone tell me how to do that ?
(I need this code to be blocking, not non-blocking)
EDIT: All my code is available on Github :
https://github.com/Fointard/NodeJs/tree/authentication
The problem lies here : https://github.com/Fointard/NodeJs/blob/authentication/js/reqHandlers/auth.js Lines 98 and 104, i'm relying on 'data' and 'end' envents but i'd like to do that asychronously so that checkID() (line 95) is able to return true or false.
You can't. HTTP Requests are I/O operations and will always be resolved asychronously. Your checkID function will never return a value. You need to add a second parameter (usually called callback) that will be called with true or false.
function checkID(req, callback) {
var body = '';
req.on('data', function (data) {
body += data;
if (body.length > 1e6)
req.connection.destroy();
});
req.on('end', function () {
var post = qs.parse(body);
if ('loginInputLogin' in post && 'loginInputPassword' in post) {
console.log('login : '+post['loginInputLogin']);
console.log('password : '+post['loginInputPassword']);
}
if (post['loginInputLogin'] === 'fointard' && post['loginInputPassword'] === 'f01n') {
console.log('ID confirmed');
callback(true);
}
callback(false);
});
}
And use it like so:
checkID(yourRequest, function(success) {
if(success) {
//login successfull
} else {
//login failed
}
})
I am creating a command line app using nodejs. For some reason whenever I enter a track (node liri.js spotify-this-song "enter track") i get a response of a random band called Nocturnal rites, song named "something undefined", and album called "grand illusion". Does anyone know where I am wrong, or why I am getting these responses?
function spotifyIt(song) {
spotify.search({ type: 'track', query: song }, function(err, data) {
if ( err ) {
console.log('Error occurred: ' + err);
return; //from spotify npm docs
}
else{
var songInfo = data.tracks.items[0];
var songResult = console.log(songInfo.artists[0].name)
console.log(songInfo.name)
console.log(songInfo.album.name)
console.log(songInfo.preview_url)
console.log(songResult);
};
});
}
Nevermind, I figured it out. had to change the query to the correct params[]... i.e it ended up looking like this
function spotifyIt() {
spotify.search({ type: 'track', query: params[1] }, function(err, data) {
if ( err ) {
console.log('Error occurred: ' + err);
return; //from spotify npm docs
}
else{
var songInfo = data.tracks.items[0];
var songResult = console.log(songInfo.artists[0].name)
console.log(songInfo.name)
console.log(songInfo.album.name)
console.log(songInfo.preview_url)
console.log(songResult);
};
});
}
I had a global variable var params = process.argv.slice(2); and a switch statement with another params[1], so that it ended up calling the fourth parameter i.e. where the song title was named in the terminal
switch(params[0]) {
case "my-tweets":
myTweets();
break;
case "spotify-this-song":
if(params[1]){ //if a song is put named in 4th paramater go to function
spotifyIt();
} else { //if blank call it blink 182's "whats my age again"
spotifyIt("What\'s my age again");
}
break;
I am using the following node.js code to download documents from some url and save it in the disk.
I want to be informed about when the document is downloaded. i have not seen any callback with pipe.Or, Is there any 'end' event that can be captured on completion of download ?
request(some_url_doc).pipe(fs.createWriteStream('xyz.doc'));
Streams are EventEmitters so you can listen to certain events. As you said there is a finish event for request (previously end).
var stream = request(...).pipe(...);
stream.on('finish', function () { ... });
For more information about which events are available you can check the stream documentation page.
Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish,
it should handle writableStream's finish event.
var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });
Code snippet for piping content from web via http(s) to filesystem. As #starbeamrainbowlabs noticed event finish does job
var tmpFile = "/tmp/somefilename.doc";
var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
// pipe done here, do something with file
});
var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
return response.pipe(ws);
});
I found an a bit different solution of my problem regarding this context. Thought worth sharing.
Most of the example create readStreams from file. But in my case readStream has to be created from JSON string coming from a message pool.
var jsonStream = through2.obj(function(chunk, encoding, callback) {
this.push(JSON.stringify(chunk, null, 4) + '\n');
callback();
});
// message.value --> value/text to write in write.txt
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");
//"close" event didn't work for me!
writeStream.on( 'close', function () {
console.log( "- done!" );
sftp.end();
}
);
//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
console.log( "- done!"
sftp.end();
}
);
// finally this worked for me!
jsonStream.on('data', function(data) {
var toString = Object.prototype.toString.call(data);
console.log('type of data:', toString);
console.log( "- file transferred" );
});
jsonStream.pipe( writeStream );
Here's a solution that handles errors in requests and calls a callback after the file is written:
request(opts)
.on('error', function(err){ return callback(err)})
.pipe(fs.createWriteStream(filename))
.on('finish', function (err) {
return callback(err);
});