Avoid using global, creating variables - javascript

I'm using Ecmascript 3 on Rhino JavaScript engine. The process starts with connecting a remote server and download scripts from there.
I need to import my JavaScript libraries that would work on Linux agent like this:
/*
#import lib/*.js
*/
init(this);
function init(){
var foo = lib.foo;
var constants = lib.constant;
////some logic here
}
So, my script agent tries to download script files from server, and it needs to import all of the libraries that I wrote up.
I already tried to use lazy loading but it's too hard to implement all files right now and idea, how could I simplify this process?

Related

How do I use node.js on a localhost:8000 server?

I have some pure JS code and HTML and CSS on my localhost:8000 server. I have installed node.js and I am able to use it without problem testing it on the VS code terminal. However, I want to integrate the file reading mechanic of node.js into the code that I am running on the localhost:8000 server. I want to put this node.js code into my webpage on localhost:8000
const {readFileSync, promises: fsPromises} = require('fs');
function syncReadFile(filename) {
const contents = readFileSync(filename, 'utf-8');
const arr = contents.split(/\r?\n/);
console.log(arr); // 👉️ ['One', 'Two', 'Three', 'Four']
return arr;
}
syncReadFile('./locations.txt');
I have tried copy and pasting it into the js file for the webpage, however when I run it, the console says
Uncaught ReferenceError: require is not defined
at window.onload (index.js:23:46)
index.js:23:46 is the line where const {readFileSync, promises: fsPromises} = require('fs'); is.
How do I fix this?
I think you need a better understanding of how NodeJS works:
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
A JavaScript runtime is (in this context) a program that runs in a machine, with tools to interact with that machine. In development, the context of that machine is the context of a Server.
Now, JavaScript found it's use in the HTML script tag, that's the most "vanilla" way to execute JS in it's home, what it's most used for. In this context, JavaScript is running as a Client.
What makes NodeJS, different from executing the same code in an HTML file you can already execute without installing NodeJS?
It's as vanilla as you can get after you "force" JavaScript to be executed in the Backend, but for it to be used as a webserver, there are some tools that need to be ported, converted or even created, some of these tools, like the File System (fs) are specific to NodeJS.
That's it! TLDR is that your code won't work because it's being executed in the wrong place. You can fix that in many ways, like this one, but maybe you can find a better path understanding how NodeJS works
Browsers cannot access file systems like that. Nodefs will not work within the browser
The NodeJS modules only works on the server side, you can't use it client side (that also include the require() syntax).
If you want to read a file from the server, you might want to use an AJAX directed to the route that has a controller to read the targeted file, which then the result of the AJAX is handled client side with vanilla JS.

JavaScript in IntelliJ rest client

I have read most if not all of the documentation JetBrains provides about their HTTP Client and how to create requests using files with .http extension.
My problem is that I want to use a function in a different .js file inside one of the .http request files. The way they explain how this can be achieved is with this 1 liner "For external scripts, you need to enable it manually." The problem is they don't explain how you do the manual part. I did find that you have add any custom js code/library via Settings-> Languages and Frameworks -> JavaScript -> Libraries.
So my question is if anyone knows how to import custom JavaScript in a different location in a .http file? My JavaScript function is written in this manner:
export default function writeResponse(response, client) { ... }
For external scripts, you need to enable it manually
This quote from the docs is about enabling code assistance for external script, not about importing and exporting functions from scripts.
For your scenario, please try load(), for example:
### Import a function check() from a script new.js
GET http://example.org
> {%
load('/Users/YourPathToScript/scripts/new.js');
check();
%}

Unable to get full path of file dropped in browser due to security reasons. What to do?

I'm developing a web-application with Django, which should manage and process a huge amount of user' files in local intranet. As the Django app and user files will host in the same local network, there is no necessity to upload files, it's ok to provide Django with full network path to the file via user's view.
I realised that it's impossible to get full file path from the browser due to security reasons.
There is a lot of files a user will process every day (around 150-200), so it's not ok to ask user to manually copy-paste full file path into the app. Initial design approach supposed user to drag-n-drop files from Windows Explorer to dedicated areas in the browser.
What's my options, community?
rewrite all front-end as Electron app (yikes! Just because of it!) and use Django only as REST API backend;
rewrite ducking everything as desktop app and lose all advantages Django provides (authorization, authentication, ORM, admin panel, gosh -- lots of it);
the third funny option
I feel a little stranded. Need some advice. Thanks!
I have encountered same problem while working on this.
When I think on your options
1- There is no need to re-write whole app
Create an api endpoint on server side
Create a script(program) on client that will push real paths to server
Your files should be accessible over network
Here is the script code that I used:
Tested with python Python 3.7.4 Prints realpath of all the selected files as a list.
source
import tkinter as tk
from tkinter import filedialog
import pathlib
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
file_path = filedialog.askopenfilenames()
# print(file_path) #debug
files = list(file_path)
print(files)
Then you need to import either a requests and generate a Json request to your server endpoint.Or just call a curl with subprocess.
2- By your definition I assume the intranet network is trusted.So is authentication necessary.And there is a question of How many users will use same file after it is processed in server.If its one then there is no need for a django app.
Well...
I've solved my problem. With much less blood than expected, which I'm happy of. :)
First, I installed Electron and one of minimal boilerplates into a new folder in my project.
In boilerplate there is a file called main.js (or index.js, depends on boilerplate), which defines Electron application window and its contents. Inside is the line which loads content to Electron BrowserWindow object:
mainWindow.loadFile(path.join(__dirname, 'index.html'));
Fortunately, BrowserWindow object does have method loadURL, which can be used to load webpage instead of local html file:
mainWindow.loadURL('http://127.0.0.1:8000');
It means that all pages rendered by Django will be shown in Electron browser, which runs node.js instead of standard browser javascript engine. Thus, this code in Django page template will work perfectly:
<h1 id="holder">DROP FILES HERE</h1>
<p id="dropped"></p>
<script>
const dropZone = document.getElementById('holder');
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
let filesList = '\n';
for (const f of e.dataTransfer.files) filesList += f.path + '\n';
document.getElementById('dropped').innerHTML = `Full file paths: ${filesList}`;
});
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
</script>

Setting up a common route for javascript calls in ASP.NET MVC project

I have a bizarre routing issue with my ASP.NET MVC project that I hope you guys can help me with.
Overall everything works fine when I run the project off my localhost or run it on the server while it's deployed directly at http://myServerName. The problems start when I deploy the application to various enviornments on the server located under different virtual directories. For example: http://myServerName/QaEnviornment or http://myServerName/TestEnviornment
The problem is that all Javascript calls to application URLs ignore my environment virtual directories and fail.
For example on my QA server whenever I have to make an Ajax call I take a standard approach such as:
var myUrl = '/ControllerName/ActionMethodName/'
$.ajax({url:myUrl,success:function(){Do stuff} })
Because my application is deployed on http://myServerName/QaEnviornment, when rendered I expect myUrl to be http://myServerName/QaEnviornment/ControllerName/ActionMethodName. Instead it comes back as http://myServerName/ControllerName/ActionMethodName and ofcourse fails.
To get around this for now I declared a global Javascript variable that contains the environment folder name and when I build URLs for javascript calls I have to remember to ALWAYS construct them as var myUrl = myGlobalFolderVar + '/ControllerName/ActionMethodName/'
Using a global JavaScript variable to get around this issue seems as a bad solution to me. Is there anything I can do to get routing to work properly so whenever JavaScript calls are made whatever subfolder the application is running under is always included in the URL ?
Instead of always having to remember to construct them correctly, make a helper function that you call to create your URLs
function CreateUrl(string path){
return myGlobalFolderVar + path;
}
To answer your second question, not really. Routing is not aware of what made the request and you cannot always rely on the X-Http-RequestedWith header to base that decision on. In addition, your site application root is not at the domain root, therefore routing would only kick in when it visits your application. The only other way I am aware of is to have MVC actually generate the Url for you (var url = '#Url.RouteUrl(params)';) but this does not help at all when you have your JavaScript in a single or a few .js files.
EDIT
The above function is a JavaScript function that can sit anywhere you would like in your application, including external JS files. As for setting your myGlobalFolderVar, there are a few ways you could set this.
1.Actually hard code the variable in your external JS file.
var myGlobalFolderVar = 'TestEnviornment';
This is hard however if you are deploying to several different testing servers.
2.If you are using web.config transformations, you could add an AppSettings key/value pair in your web.config transformations depending on build type. Then, using that value, set your global Javascript variable in your master page layout/views.
<appSettings xdt:Transform="Replace">
<add key="folderLocation" value="TestEnvironment" />
</appSettings>
In your external JS file
//this makes it a site wide/global variable in any place you
//include your external JS file
var myGlobalFolderVar = '';
And in your master view
<script type="text/javascript">
myGlobalFolderVar = '#ConfigurationManager.AppSettings["folderLocation"]'
</script>
3.Same as number two, but use the URL helpers to figure out what the path to your application is in your master view instead of using the web.config transformations
<script type="text/javascript">
myGlobalFolderVar = '#Url.Content("~/")'
</script>
The basic idea is using .NET to figure out where it lives and set a global JavaScript variable with that path information. Then, in conjunction with the helper JavaScript function provided at the top of this answer, you can correctly generate paths as needed throughout your application - regardless of path depth, deployment location or any other deployment type concerns.
var myUrl = CreateUrl('/ControllerName/ActionMethodName/');
$.ajax({url:myUrl,success:function(){Do stuff} });

How do I automate Javascript and CSS minification on Google App Engine?

I couldn't find any proper solution for automating Google App Engine CSS and Javascript minification.
If your JS/CSS files are to be used inside an HTML page, then a very good option is to have App Engine optimize your site automatically (minification, bundling, inlining and more) via the experimental "Page Speed" feature. You can turn this on by doing this:
Go to your projects' App Engine dashboard:
https://appengine.google.com/settings?&app_id=s~your_project_id
Click on "Application Settings" (bottom left under "Administration" section).
Scroll down to the "Performance" section and locate "PageSpeed Service:". Check the " Enable PageSpeed Service" checkbox and hit "Save".
This will add response filters that will automatically do stuff like combine and minify your JS, turn the minified bundle from a script reference to an inline script (to lesser the count of server requests) and more cool and effortless performance improvments. Read more about this feature here: https://developers.google.com/speed/pagespeed/service/faq
Write a deploy script that makes a copy of your app with minified JS and CSS, and then calls appcfg on it. You shouldn't be minifying it dynamically unless you're generating it dynamically.
I ended up creating this appengine script (uses memcache and slimit).
I found slimit to be the best minification script all around, but I'm thinking about using the one from Google instead.
http://ronreiterdotcom.wordpress.com/2011/08/30/automatic-javascript-minification-using-slimit-on-google-app-engine/
You can automate the process pretty efficiently by loading the content of your script into a string, processing it with jsmin and finally save and serve the result. Don't worry about performance, you only run jsmin when the application instance is created (certainty not for every request).
you can grab jsmin.py here.
lets say I have this function that reads the JS from the filesystem (uncompressed, debug version) and returns it's string content in the logger.py module:
class ScriptManager():
def get_javascript(self):
path_to_js = os.path.join(os.path.dirname(__file__), 'js/script.js')
return file(path_to_js,'rb').read()
process it over with jsmin. make sure to use proper caching headers. take this jsrendered sample module as an examp
js_compressed =
jsmin.jsmin(scripts.logger.ScriptManager().get_javascript())
JS_CACHE_FOR_DAYS = 30
class scriptjs(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/javascript'
expires_date = datetime.datetime.utcnow() + datetime.timedelta(JS_CACHE_FOR_DAYS)
expires_str = expires_date.strftime('%d %b %Y %H:%M:%S GMT')
self.response.headers.add_header('Expires', expires_str)
self.response.headers['Cache-Control'] = 'public'
self.response.cache_control.no_cache = None
self.response.out.write(js_compressed)
now return that from a dynamic contnet handler in your main.py:
app = webapp2.WSGIApplication([
('/scripts/script.js', jsrender.scriptjs),...
Nick's answer is the correct way to do it, but you could do it on the fly when the JS/CSS is requested - then set cache-control to public to cache the results upstream.
Slimmer - http://pypi.python.org/pypi/slimmer/
JSmin.py -
http://code.google.com/p/v8/source/browse/branches/bleeding_edge/tools/jsmin.py
Cache control header chatter -
http://groups.google.com/group/google-appengine/browse_thread/thread/be3fa7b5e170f378 and blog post - http://www.kyle-jensen.com/proxy-caching-on-google-appengine
You could try a build-time or a runtime solution (using maven plugin) provided by a tool called wro4j
Disclaimer: this is a project I'm working on.

Categories

Resources