Write a variable to a file in Javascript - 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.

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.

How to write file in Google Chrome App without prompting?

I am fumbling around with the free Chrome Dev Editor on my Chromebook. I am trying to use the fileSystem to read and write .txt files. It is all very wrapped up, not at all like in C. I can no more tell if I am even allowed to do something, let alone where the proper place is to find out how.
I think the files I can see using the Files thingy are in the sandbox that I am allowed to play in (meaning, folders that are accessible by the app?) The root is called Downloads. Sure enough, if I use all the dot calls and callback arguments for the read, as in the examples at developer.chrome.com/apps/filesystem, it works. But I have to have a prompt
every time for both reads and writes.
A little more Googling came up with this trick: (I think it was here in stackoverflow, in fact) a chrome.runtime call, getPackagedDirectoryEntry, that seems to give me a handle to the folder of my app. Great! That's all I need to not have to go through the prompting. For the readfile, anyway.
But then trying to apply the same trick to the writefile did not work. In fact, it did nothing discernible. No errors, no complaints. Nothing. Even though the write file with prompting works fine (so presumably I have the permissions and Blob construction right.) What to do?
Here is my code:
function test(){
// Samsung 303C Chromebook - Chrome Dev Editor - /Downloads/Daily/main.js
// prompted write
chrome.fileSystem.chooseEntry({type:'saveFile'},function(a){
a.createWriter(function(b){
b.write(new Blob(["Programming fun"],{type:'text/plain'}));
},function(e){trace.innerText = 'error is ' + e;});
});
// unprompted read
chrome.runtime.getPackageDirectoryEntry(function(a){
a.getFile('text.txt',{},function(b){
b.file(function(c){
var d = new FileReader();
d.onloadend = function(){trace.innerText = this.result;};
d.readAsText(c);
});
});
});
// unprompted write - why not?
chrome.runtime.getPackageDirectoryEntry(function(a){
a.getFile('new.txt',{create:true},function(b){
b.createWriter(function(c){
c.write(new Blob(["Miss Manners fan"],{type:'text/plain'}));
},function(e){trace.innerText = 'error is ' + e;});
});
});
}
To be fair, Filesystem API is a big mess of callbacks and it's not unreasonable to get drowned in it.
It's not currently documented, but chrome.runtime.getPackageDirectoryEntry returns a read-only DirectoryEntry, and there is no way to make it writable (it's specifically blacklisted).
You probably don't see an error, because it fails at the getFile stage, for which you don't have an error handler.
Unfortunately, for a Chrome App the only option to write out to a real filesystem is to prompt the user. However, you can retain the entry and ask only once.
If you don't need to write out to the real filesystem but need only internal storage, HTML Filesystem API can help you (yes, it's marked as abandoned, but Chrome maintains it since chrome.fileSystem is built on it).
Extensions additionally have access to chrome.downloads API that enables writing to (but not reading) the Downloads folder.
P.S. What you see in Files app is your "real" local filesystem in ChromeOS + mounted cloud filesystems (e.g. Google Drive)
You can use the basic web Filesystem API. First, add the "unlimitedStorage" permission. Then, copy the packaged files to the sandboxed filesystem, like this:
chrome.runtime.getPackageDirectoryEntry(function(package) {
package.getMetadata(function(metadata) {
webkitRequestFileSystem(PERSISTENT, metadata.size, function(filesystem) {
package.copyTo(filesystem.root)
})
})
})

Execute javascript without webview in Android

I'm trying to execute a JS fonction in my Android app.
The function is in a .js file on a website.
I'm not using webview, I want to execute the JS function because it sends the request i want.
In the Console in my browser i just have to do question.vote(0);, how can I do it in my app ?
UPDATE 2018: AndroidJSCore has been superseded by LiquidCore, which is based on V8. Not only does it include the V8 engine, but all of Node.js is available as well.
You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());
JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");
However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.
Is there a reason you don't use a hidden WebView and simply inject your code?
// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);
For the future reference, there is a library by square for this purpose.
https://github.com/square/duktape-android
This library is a wrapper for Duktape, embeddable JavaScript engine.
You can run javascript without toying with WebView.
Duktape is Ecmascript E5/E5.1 compliant, so basic stuff can be done with this.

How run a windows console for 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.

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.

Categories

Resources