How run a windows console for JavaScript - javascript

I would like to have a console window (a command line) on Windows 7 which will allow me to play with JavaScript just like a python console.
Update:
It's important to have a file access from within the console (or script run through it).

You can use Node.js's REPL. To do so follow this steps:
Download and Install Node.js.
Call Node.js from the Start Menu / Start Screen or directly node.exe installation path (e.g C:\Program Files\nodejs\node.exe).
Enjoy!
You may want to add the installation path to your PATH enviroment variable for ease of use.
Note: to leave node.js press Ctrl + C twice.
To access the local files, you will need the File System module. This is an example of usage:
var fs = require("fs");
fs.readFile(
"C:\\test.txt",
function(err, data)
{
if (!err)
console.log(data.toString());
}
);
This will output the contents of the file C:\test.txt to the console.
Note: An unhandled exception will cause node.js to "crash".

You can just use the developer tools.
For example, in Chrome, press F12. This will bring up the developer tools. The last option on the menubar is console. This will allow you to create JS variables and functions and to interact with DOM elements on the current page

It's possible thanks to Mozilla Rhino JavaScript Engine.
To create a console window for JS:
1) Download Mozilla Rhino JavaScript Engine binary.
2) Extract: js.jar.
3) Create a script to run the console window (e.g. rihno_console.bat):
java -cp js.jar org.mozilla.javascript.tools.shell.Main
For more information about usage (for instance, and global functions inside this console) visit the Rhino Shell web page.

Just like I informed another user with the same question as yours who was faced with the same need, check out DeskJS (https://deskjs.wordpress.com). It's a portable Windows console application that lets you run pure JavaScript code and even load any existing JS files. It supports even the basic JS popup boxes implemented in browsers. You can save your commands as JS files that can be run on startup or by dragging-and-dropping them on the app. Plus there's so much more to it like you can create a build system for Sublime Text that can run JS files via cmd, it supports themes for customizing the entire console and snippets which let you save short snippets of JavaScript code for later use. Improvements are still being made on the app together with other native APIs being included. Hope this helps you as it did for me.

Related

What native javascript method is capable of creating a server?

I am new to nodejs. I have successfully installed it on my computer (and rebooted). I have created a hello_world.js inside My Documents directory (I'm on a windows xp computer):
console.log("hello world");
var my_http = require( 'http' );
var my_server = my_http.createServer( ... ) ;
...
I have successfully opened a windows command prompt, cd'd to the My Documents directory, executed the .js file, and received 'hello world' output. And I have navigated my browser to the running localhost port (for my experiment: http://localhost:1337/)
But I have 2 major questions based on this:
1 - where is 'http' ... I suppose it is a module(?), but I do not find such a directory within my nodejs installation directory.
2 - how does the http method, createServer, actually create a server? Does native javascript have such a method?
The node.js standard library is written in Javascript and C++, and C++ modules can be loaded in js code via process.binding. Specifically for http.createServer, it's a wrapper around _http_server.Server, which invokes net.Server, which uses the C++ TCP wrapper .
See here for more details.
To answer the second question, createServer just creates and populates the control object, the actual work is in listen, which first creates a handle and this is where C++ code is actually called for the first time.
1) http is a built-in node module. You can read up on the documentation for it here: https://nodejs.org/api/http.html. Node provides a lot of modules out of the box to assist w/ everyday operations (interacting w/ file systems, making HTTP requests, creating servers, working with paths, etc.)
2) Not sure what you mean by "native" JavaScript. JavaScript is just a language. I think you're really asking about the runtime environment. If you are using JavaScript in the browser, then no you can't start an HTTP server. But Node.js runs on the server, so in this environment it can do all sorts of stuff that you can't do w/ JavaScript in the browser, such as access the file system.

Write a variable to a file in Javascript

This may be a copy.. but I'm not getting the thing I want from the answers I saw..
I just want to save a particular variable into a local file using Javascript. I know how to read a file.
I wrote this code..
<script>
var fs = require('fs');
fs.writeFile('http://localhost/online/hello.txt', 'Hello Node', function (err) {
if (err) throw err;
else
{
console.log('It\'s saved!');
}
});
</script>
What is the error here.. or is there a simple and straight-forward way of doing it..??
It seems you're trying to call node-js code from the browser. Although javascript can run in both the browser and on the server (node-js), those are separate systems.
Another thing you can do is google "HTML save file example" and see how this is typically implemented - by opening a save dialog for the user, getting his/her permission, etc. (otherwise any website could just write any file to your computer...).
You are writing NodeJS code for client side application. You must understand the difference between javascript on browser and javascript on NodeJS platform.
Javascript is a language just like C, Java and Python
V8 is a javascript engine to run the javascript application. It is something similar to JRE for Java.
Browser(Only Chrome) uses V8 engine for running javascript application. Other browsers use different javascript engine. Five years ago, there was only one possibility that javascript can only work on browser. You cannot use javascript for application programming like C and Java
NodeJS is a platform which uses V8 to enables developer to write javascript application just like C, Java program. NodeJS also has some inbuilt library for accessing file system,
networks, and much more utilities. One of the internal library in NodeJS is fs. It only works on NodeJS application, not on browser application.
This can be done pretty simply using jrpc-oo. jrpc-oo links the browser and nodejs using the JRPC2 protocol. jrpc-oo abstracts classes over JRPC so that either side (nodejs or the browser) can call eachother.
I have setup an example repo to do exactly this here. Use the writeToFile baranch. I will break out the important parts here.
First in nodejs, we write a class with a method to write input arguments to file. The method looks like so (from the file TestClass.js) :
const fs = require('fs');
class TestClass {
writeToFile(arg){
fs.writeFileSync('/tmp/browser.json',JSON.stringify(arg));
}
}
In the browser we inherit from the jrpc-oo class JRPCClient and call the server class TestClass and method writeToFile like so (from the file src/LitJRPC.js) :
import {JRPCClient} from '#flatmax/jrpc-oo/jrpc-client.js';
export class LitJRPC extends JRPCClient {
writeObjToFile(){
// create the argument we want to save to file
let dat={name:'var',value:10};
// Ask the server to execute TestClass.writeToFile with args dat
this.server['TestClass.writeToFile'](dat);
}
}
Finally we run the nodejs app and the web-dev-server and we look at the browser console and nodejs console to see what happened. You will see the browser variable dat saved to the file /tmp/browser.json
As we are using a secure websocket for jrpc, you will need to generate the certificate and clear the certificate with the browser before the app will work. If you don't want to worry about security then don't use secure websockets. Read the readme in the reference repo for more information on setup and usage.

JavaScript: "Uncaught SecurityError" when running JS-XSL demo locally

(This question pertains to the JS-XSL demo found here)
To briefly tell you what this demo is for; it takes a MS Excel file as input, parses the data, and outputs the data in text-only format. I downloaded the package (zip) and ran it locally, simply by opening the html file with Chrome.
The problem is, I just cannot seem to get over the following error:
Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///C:/Users/David/Desktop/Xlsx%20Demo/xlsworker.js' cannot be accessed from origin 'null'.
And above error points to line 34 of the html file, which has the following code:
/* I changed the file path from './xlsworker.js' to 'xlsworker.js' */
var worker = new Worker('xlsworker.js');
There are only three files for this demo: the html file itself, and two javascript files, one is named xls.js and the other xlsworker.js. All three files are in the same directory and at the same level.
What's rather baffling to me is, I successfully ran this same demo about a couple months ago! I cannot imagine if I am doing anything differently now. Any insight?
https://code.google.com/p/chromium/issues/detail?id=278883#c9
You are basically prevented by Chromium to use workers on the file:// protocol, you have to host your files and access them through the http:// protocol.
You need a server (even something simple like http://docs.python.org/2/library/simplehttpserver.html)
IMO, the below is a superior answer, because it does not require running a web-server. It's extremely quick and simple.
(the downvote is explained in my Note 5, below)
I have tested and verified that this solution works with the demo linked by the asker, when run locally as described by the asker. Tested on Windows 10, Chrome Stable x64 48.0.2564.103 m.
A script is not allowed to access to your local file system in Chrome. If you'd like to test web workers locally, you have to open Chrome with a special flag.
On Windows, launch chrome with the flag:
chrome.exe --allow-file-access-from-files
After that Chrome will be launched and you can test workers during this session.
Note1: if Chrome is already running when you run this command, the new instance of Chrome will not allow Workers to run-- you must first exit from Chrome (if necessary, use Windows Task Manager to ensure Chrome is not running).
Note 2: the source for this answer (link below) includes the --args flag on Windows, but i have not found the "args" to be necessary on Windows. In fact, i cannot find any documentation of the "args" flag anywhere-- not sure what it does. So i don't include it in the Windows command, above.*
Note 3: For those trying to do something similar on Chrome-Mac, or Windows-Firefox, the link below includes both, along with the Windows-Chrome solution above. But my solution described above is only the Windows-Chrome method.
http://js-workout.tompascall.com/web-workers-and-responsiveness/
Note 4: Be aware that this solution is not the same as running a web-server, but for your purpose it should be a completely adequate solution. Also, be aware that to browse the web with this chrome startup-switch enabled may compromise your local file-security, so it's advised to only use this method for your local file purpose, and disable it for web-browsing.*
Note 5: Google states that using startup flags "should only be used for temporary cases and may break in the future." Web search for chrome startup switches returns about 2,000 hits, so lots of people use them and blog about them. If your need is temporary, then this currently works great.*

run exe file in local machine using chromium

I need to run an exe file from a html file wrapped into chromium.
I used http://crportable.sourceforge.net to wrap the application into Chromium.
The following code is not working, nothing is actually happening:
function runFile() {
alert('opening file');
w = new ActiveXObject("WScript.Shell");
w.run('C:/Windows/notepad.exe');
return true;
}
before going ahead and tell me that this is a breach of security or that I am an hacker let me explain what I am trying to do. My application run locally (wrapped into chromium) and it need to run an exe file created in Delphi that process a local power point presentation.
I am trying to run notepad.exe just to prove I can run a local file.
Can you help?
Thank you very much
What you're trying to do is not allowed by default. But you can write a C++ method which is available in your Javascript. This C++ method can actually run your application.

Debug Javascript in netbeans 7.4 inside PHP project

I want to debug javascript code inside my php project in netbeans. I have read on several occasions that this should be possible in the new netbeans 7.4 version, for example here and here, but i cannot get it to work. I have installed de debugger connector for chrome and php debugging works just fine but when i try to set a breakpoint in a .js file it says:
unresolved breakpoint,
debugger is not attached to tab with id....
i understand that the link from the netbeans page is for an html 5 application but i thought this debugging would also be enabled in php projects. Am i doing something wrong?
i know i can debug with firebug or chrome itself but i would like to do it all in one place in my netbeans IDE...
thanks in advance
The unresolved breakpoint usually mean that for instance you set it in file that is not loaded in Chrome's tab right now (or for some reason, IDE cannot match URL of JS file and local JS file). The mixed debugging works only in Embdded Browser or in Chrome with NetBeans connector (you can see the usually yellow bar in your page saying "NetBeans connector is debugging this page" and you can debug PHP and JS at the same time.
Have a look here, although it is about Java EE projects, it is very similar to PHP projects
Updated answer:
One issue I remember (and plain Chrome Dev Tools has it as well) is that if you have JavaScript file attached to HTML/PHP with dynamic parameter to prevent browser from caching, e.g. , where "673612" changes each time a file is loaded. If that's your case, try to remove this dynamic attribute. I think that e.g. Sencha or ExtJS use this feature which "breaks" debuggers.
I had a similar problem : javascript breakpoints were broken, while everything else was working fine (for example php breakpoints were okay).
The reason was that in the run configuration properties I changed the Project URL to something that was not the host anymore, but a subfolder managed by a url rewriting rule.
johanvs is correct, but my reputation is not enough to +1.
Suppose a NetBeans project contains many files in different folders:
/var/www/index.html
/var/www/config.html
/usr/doc/readme.txt
/usr/doc/license.txt
Since "index.html" is not in the project root folder but under "/var/www", NetBeans does not know "http://127.0.0.1/index.html" is corresponding to "/var/www/index.html". To solve, verify below settings in NetBeans -> File -> Project Properties:
Sources -> Web Root
"var/www"
Run Configuration -> Project URL
"http://127.0.0.1/"
Run Configuration -> Index File -> Browse
"index.html"
Run Configuration -> Remote Connection -> Manage -> Initial Directory
"/"
Run Configuration -> Upload Directory
(empty)

Categories

Resources