I'm attempting to write a script which is able to take a screenshot given an url using phantom.js. This works great when I supply the url(s). However, I would like to be able to read urls from a file in much the same way as in:
here and here. However, all methods return with
unable to open file 'filename.txt'
Am I missing something here?
Working from a win7 installation.
EDIT:
var fs = require('fs');
var file_h = fs.open('urls.txt', 'r');
var line = file_h.readLine();
while(line) {
console.log(line);
line = file_h.readLine();
}
file_h.close();
The output I get is:
unable to open file 'urls.txt'
phantomjs://platform/fs.js:79 in open
I have a problem with my small demo for live query as in attached image.
To be honest, I have no idea why does it go wrong. Try to find some solutions around but not yet successfully. Please give me some ideas or solutions if you know this issue. Thanks so much.
Parse server example: 1.4.0
Parse JS SDK: 1.10.2
NodeJS: 8.9.1
npm: 5.5.1
P/S: I have added classes for supporting by Live Query already.
Here is the source which run successfully without using Live Query
Link to src with removed parse link:
var Parse = require('parse/node');
Parse.initialize("shetei5aeJ9Aequi6deejojiv7foh6Hieg2eesh9keingohw");
Parse.serverURL = 'serURLhere';
var Node = Parse.Object.extend('Node');
var q = new Parse.Query('Node');
var subscription = q.subscribe();
var procEventOpen = () => {
console.log('subscription opened...');
};
subscription.on('open', procEventOpen);
This happened to me when I had a typo in server url.
Try to explicit specify liveQueryServerURL parameter:
Parse.liveQueryServerURL = 'ws://yourserverurl/parse';
Note the ws instead of http(s)
I use the following command when building an ionic project for desktop
ionic cordova build browser --prod
Which results in the following file being generated
build/main.js
However I would like to be able to add a version number to the generated file automatically as part of the build process. So would end up with something like
build/main.js?version=1.00
as to avoid needing to clear the browser cache after every prod build.
Is there a flag for this, or is it something I must do manually?
Any advice would be great!
EDIT:
My solution is on GitHub for anyone interested!
https://github.com/RichardM99/ionic-3-version-build-file-hook
Here's some advice - You can create a cordova hook.
Hooks are scripts that you want to be executed at different stages of the build process. In your case, you are looking at a script which renames the main.js file after the build event is finished, or in other words a 'after_build' type hook.
The script will usually be a Node.js file, although you can have other types of scripts executed as well.
One more thing. Since you want to get around cache, you wont be renaming the file itself. What you will want to do is rather replace the reference to "main.js" in you "index.html" to include a random or maybe your actual version number.
I have pointed you in a direction, but won't spoonfeed. Look up documentation on cordova hooks. They are super simple if you understand Javascript/Node
Something like this should get the job done:
var index_orig = fs.readFileSync(path-to-index.html, 'utf8');
var index_new = index_orig.replace("main.js", "main.js?version="+version_num);
fs.writeFileSync(path-to-index.html, index_new, 'utf8');
If you want the actual build number, you can read your config.xml and parse it to get it's value.
Hope it helps.
I wrote blog long time ago
In my build pipeline i have command to set version
version "$(app.versionPrefix)$(Build.BuildNumber)"
$(app.versionPrefix) - is a prefix version such as 0.1.
$(Build.BuildNumber) - is build version
Then I have environment file
export const environment = {
apiUrl: 'https://....',
production: true,
version: '0.0.57'
}
Then i have js script to update version in environment and config.xml
var replace = require('replace-in-file');
var package = require("./package.json");
var buildVersion = package.version;
const options = {
files: ['config.xml'],
from: /" version="([0-9]*.[0-9]*.[0-9]*)"/g,
to: "\" version=\""+ buildVersion + "\"",
allowEmptyPaths: false,
};
const optionsEnv = {
files: ['src/environments/environment.prod.ts'],
from: /version: '(.*)'/g,
to: "version: '"+ buildVersion + "' ",
allowEmptyPaths: false,
};
try {
let changedFiles = replace.sync(options);
if (changedFiles == 0) {
throw "Please make sure that file '" + options.files + "' has \"version: ''\"";
}
changedFiles = replace.sync(optionsEnv);
if (changedFiles == 0) {
throw "Please make sure that file '" + optionsEnv.files + "' has \"version: ''\"";
}
console.log('Build version set: "' + options.to + '"');
}
catch (error) {
console.error('Error occurred:', error);
throw error
}
NOTE: you need to install plugin replace-in-file
Then in build pipe line I am running this script
node ./replace.build.js
In your case if you need only for browser you can tune script.
I am searching a way to prettify Json files in a node.js script (not CLI). I found a lot of npm beautifier packages, but none that can simply beautify directly a file.
There is esbeautifier that do what I am searching to do, but the exemples only shows CLI commands: https://github.com/royriojas/esbeautifier Is there a way to use it in a Javascript?
You can prettyprint JSON easily by providing parameters to JSON.stringify().
Many people use this kind of call to prettyprint JSON output. It's still valid JSON, it just contains indentation and newlines.
JSON.stringify(myObject, null, 2);
you can use the tool esformatter.
edit by #jck: here is JS snippet that works using fs:
var esformatter = require('esformatter');
var fs = require('fs');
var filename = "./myFile.json";
var codeStr = fs.readFileSync(filename).toString();
var formattedCode = esformatter.format(codeStr);
fs.writeFile(filename, formattedCode);
Alternatively, check out prettyjson! It has been great for me!
How to get the directory of a file?
For example, I pass in a string
C:\Program Files\nant\bin\nant.exe
I want a function that returns me
C:\Program Files\nant\bin
I would prefer a built in function that does the job, instead of having manually split the string and exclude the last one.
Edit: I am running on Windows
I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.
path = path.substring(0,path.lastIndexOf("\\")+1);
If you use Node.js, path module is quite handy.
path.dirname("/home/workspace/filename.txt") // '/home/workspace/'
Use:
var dirname = filename.match(/(.*)[\/\\]/)[1]||'';
*The answers that are based on lastIndexOf('/') or lastIndexOf('\') are error prone, because path can be "c:\aa/bb\cc/dd".
(Matthew Flaschen did took this into account, so my answer is a regex alternative)
There's no perfect solution, because this functionality isn't built-in, and there's no way to get the system file-separator. You can try:
path = path.substring(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")));
alert(path);
Path module has an inbuilt function
Yes, the inbuilt module path has dirname() function, which would do the job for you.
const path = require("path");
file_path = "C:\\Program Files\\nant\\bin\\nant.exe" \\windows path
file_path = "C:/Program Files/nant/bin/nant.exe" \\linux path
path.dirname(file_path); \\gets you the folder path based on your OS
I see that your path is neither windows nor Linux compatible. Do not hardcode path; instead, take a reference from a path based on your OS.
I generally tackle such situations by creating relative paths using path.join(__dirname, "..", "assets", "banner.json");.
This gives me a relative path that works regardless of the OS you are using.
function getFileDirectory(filePath) {
if (filePath.indexOf("/") == -1) { // windows
return filePath.substring(0, filePath.lastIndexOf('\\'));
}
else { // unix
return filePath.substring(0, filePath.lastIndexOf('/'));
}
}
console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin');
Sorry to bring this back up but was also looking for a solution without referencing the variable twice. I came up with the following:
var filepath = 'C:\\Program Files\\nant\\bin\\nant.exe';
// C:\Program Files\nant\bin\nant.exe
var dirpath = filepath.split('\\').reverse().splice(1).reverse().join('\\');
// C:\Program Files\nant\bin
This is a bit of a walk through manipulating a string to array and back but it's clean enough I think.
filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
split string into array delimited by "/"
drop the last element of the array (which would be the file name + extension)
join the array w/ "/" to generate the directory path
such that
"/path/to/test.js".split("/").slice(0,-1).join("/") == "/path/to"
And this?
If isn't a program in addressFile, return addressFile
function(addressFile) {
var pos = addressFile.lastIndexOf("/");
pos = pos != -1 ? pos : addressFile.lastIndexOf("\\");
if (pos > addressFile.lastIndexOf(".")) {
return addressFile;
}
return addressFile.substring(
0,
pos+1
);
}
console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin\\');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin/nant/');
console.assert(getFileDirectory('/usr/thisfolderhaveadot.inhere') === '/usr/');
The core Javascript language doesn't provide file/io functions. However if you're working in a Windows OS you can use the FileSystemObject (ActiveX/COM).
Note: Don't use this in the client script-side script of a web application though, it's best in other areas such as in Windows script host, or the server side of a web app where you have more control over the platform.
This page provides a good tutorial on how to do this.
Here's a rough example to do what you want:
var fso, targetFilePath,fileObj,folderObj;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileObj = fso.GetFile(targetFilePath);
folderObj=fileObj.ParentFolder;
alert(folderObj.Path);