How to read the real time changes in a file with CasperJS - javascript

I am trying to let my CasperJS script read an outside txt file (abc.txt), and the abc.txt needed to be created in the middle of the CasperJS process.
(and that abc.txt has to be create using 'curl' for some third party api, so I called a childprocess to renew the old abc.txt).
However, the information inside abc.txt seems locked at the begging, it doesn't matter whether I changed the information or delete the whole file.
Has anyone any idea if CasperJS can be more interactive?
or any advice if I need to change the whole script?
(I am trying to get a question from websiteA, then go to websiteB find the answer, then submit the answer in websiteA)
var casper = require('casper').create();
var fs = require('fs');
var data = fs.read('abc.txt');
casper.start();
casper.wait(5000, function () {
console.log('wait 5000 for editing the file');
});
casper.then(function (){
console.log(data);
});
casper.run();

If the content of data.txt changes, during the execution of your script, this doesn't have any influence on variables that hold a copy of the content of that file. There is never a direct connection between the string value and the file content.
If you want to refresh the string content, you need to read that file again:
data = fs.read('abc.txt');
If you need to wait for the change of the file, then you can periodically read the file contents to see if they changed in the mean time. This can be done with casper.waitFor():
var casper = require('casper').create();
var fs = require('fs');
var data = fs.read('abc.txt');
var newData;
casper.start();
casper.waitFor(function _check(){
newData = fs.read('abc.txt');
return data !== newData;
});
casper.wait(1000); // additional wait to make sure that the file writing has finished
casper.then(function (){
console.log(newData);
});
casper.run();

Related

How to download a file in the browser directly from the node.js server side without any variable?

My app is created with mean and I am a user of docker too. The purpose of my app is to create and download a CSV file. I already created my file, compressed it and placed it in a temp folder (the file will be removed after the download). This part is in the nodejs server side and works without problems.
I already use several things like (res.download) which is supposed to download directly the file in the browser but nothing append. I tried to use blob in the angularjs part but it doesn't work.
The getData function creates and compresses the file (it exists I can reach it directly when I look where the app is saved).
exports.getData = function getData(req, res, next){
var listRequest = req.body.params.listURL;
var stringTags = req.body.params.tagString;
//The name of the compressed CSV file
var nameFile = req.body.params.fileName;
var query = url.parse(req.url, true).query;
//The function which create the file
ApollineData.getData(listRequest, stringTags, nameFile)
.then(function (response){
var filePath = '/opt/mean.js/modules/apolline/client/CSVDownload/'+response;
const file = fs.createReadStream(filePath);
res.download(filePath, response);
})
.catch(function (response){
console.log(response);
});
};
My main problem is to download this file directly in the browser without using any variable because it could be huge (like several GB). I want to download it and then delete it.
There is nothing wrong with res.download
Probably the reason why res.download don't work for you is b/c you are using AJAX to fetch the resource, Do a regular navigation. Or if it requires some post data and another method: create a form and submit.

Download a json file from a link using Node js

I need to write an application with Node JS which given a link to a json file e.g http://data.phishtank.com/data/online-valid.json (The link doesn't open the file it opens a download), the program simply downloads the object and then prints it out. How can this be achieved? This is what I have so far and it doesn't seem to be working:
var checkIfPhishing = function(urlToPrint){
var http = require('http');
var fs = require('fs');
var file = fs.createWriteStream("SiteObject.json");
var request = http.get(urlToPrint, function(response) {
response.pipe(file);});
var siteObj= fs.readFileSync("SiteObject.json");
console.log(siteObj);
};
Thank you!
You cannot mix up async and sync reads and writes.
In your case you start Streaming the data from the other server to yours, but then you already start the sync read. Wich blocks the thread so the stream will be processed after youve read your 0 byte file...
So you need to store the stream in a variable first, then on finish log that stream.
So Simply do sth like this:
var data="";
var request = http.get(urlToPrint, function(response) {
response.on("data",append=>data+=append).on("finish",()=>console.log(data));;
});
Store the asyncly provided chunks of the stream in a variable, if the stream finishes log that string.
If you want to store it too:
var http = require('http');
var fs = require('fs');
function checkIfPhishing(urlToPrint){
var file = fs.createWriteStream("SiteObject.json");
var request = http.get(urlToPrint, function(response) {
response.on("finish",function(){
console.log( fs.readFileSync("SiteObject.json",{encoding:"utf8"}));
}).pipe(file);
});
}
This is exactly like your code, but it waits for the stream to finish before it reads synchronously...
However note that the sync read will slow down the whole thing, so you might directly stream to the console/a browser..

Print Image in Server side on Button Click by Client [duplicate]

Ok, so I'm trying to print from a webpage (the typical "print" button, but I don't want the print dialog to appear) so I decided to use my already existing node.js backend to do the task (mainly because printing from browser is nearly impossible without the printing dialog).
I found the node-printer (https://github.com/tojocky/node-printer) module, and it works great, but only with text. I tried to send RAW data, but what it does is printing the raw characters. What I actually need is to print a logo, along with some turn information (this is for a customer care facility).
Also, the printer must be installed locally, so I can't use IPP.
Is there any way to print an image, or a combination of images and text with node.js? can it be done through node-printer or is there another way?
I ended calling an exe to do the work for me. I use a child_process to call printhtml, which does all the printing work for me. My code ended this way:
var exec = require('child_process').exec;
exec('printhtml.exe file=file.html', function(err, data) {
console.log(data.toString());
});
Actually, you can print image using node-printer. This work for me
var Printer = require('node-printer');
var fs = require('fs');
// Get available printers list
var listPrinter = Printer.list();
// Create a new Pinter from available devices
var printer = new Printer('YOUR PRINTER HERE. GET IT FROM listPrinter');
// Print from a buffer, file path or text
var fileBuffer = fs.readFileSync('PATH TO YOUR IMAGE');
var jobFromBuffer = printer.printBuffer(fileBuffer);
// Listen events from job
jobFromBuffer.once('sent', function() {
jobFromBuffer.on('completed', function() {
console.log('Job ' + jobFromBuffer.identifier + 'has been printed');
jobFromBuffer.removeAllListeners();
});
});
I had success with the Node IPP package https://www.npmjs.com/package/ipp.
The example code on the docs, which uses another node module PDFKIT to convert your html/file into a PDF, does not work. See my answer here: Cannot print with node js ipp module for a working example.

using node.js with html

Basically, I want to use this feed:
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
console.log('title; ', article.title);
});
to show all news feeds in my HTML web page. However, I'm using node.js to run the web server at (localhost:8080). I have a separate file for the web server (index.html, style.css and client.js).
Instead of using console.log to show the news feed, I want it to appear on my webpage in my text area called alltext which is in the index.html, instead of it being printed to the console.
You can do it via various ways two of them are being mention below :
Using Sockets
var io = require('socket-io');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
io.emit('article', article.title);
console.log('title; ', article.title);
});
Now you can listen article event on webpage and display your result.
Now, Second way is traditional one. You have to save the feeds in DB and then use api to get all The Feeds you saved earlier in DB.
Thanks

Firefox-SDK contentScript returns null

I am currently writing a Firefox-Addon that automatically prints every new file from my schools website. All the files on the website are in a table and every row (where each file is) has the class "s2d". This is what i have so far:
var self = require("sdk/self");
var uploads;
pageWorker = require("sdk/page-worker").Page({
contentURL: "http://uchronski.de/lernmaterialien/beruflicheschulformen/11fosinformationssystemeundnetzwerktechnik/index.php",
contentScript: ['var uploads = document.getElementsByClassName("s2d");', 'self.port.emit("pageEntriesLenght", uploads.lenght);']
});
pageWorker.port.on("pageEntriesLenght", function(files) {
uploads = files;
});
Here i'm trying to get the current amount of files hosted on the website but "files" is alway null. I have tried it with a pageMod, which worked, but I need to do it with a page worker instead and I have no idea what I did wrong.
You made a spelling mistake in the word 'length' in the contentScript. Try this:
contentScript: ['var uploads = document.getElementsByClassName("s2d");', 'self.port.emit("pageEntriesLenght", uploads.length);']

Categories