How to properly restore Javascript context in v8? - javascript

I want to do the following:
execute a Javascript file with v8
open a REPL which evaluates code in the exact same context as the code
Any variables or functions defined in the code file, for instance, should be available in the REPL. (I'll note this used to work many v8 versions ago, but I can't figure out how to get it working in current v8 (node 0.12 == v8 3.28.73).)
I use a simple class JSInterpreter which has an isolate and a persistent context object as member vars. They gets set up when the class is initialized, and bindings also happen at that time.
When it's time to interpret some code, I call this method:
Str JSInterpreter::InterpretJS (const Str &js)
{ v8::Isolate::Scope isolate_scope (isolate_);
v8::HandleScope handle_scope (isolate_);
// Restore the context established at init time;
// Have to make local version of persistent handle
v8::Local <v8::Context> context =
v8::Local <v8::Context>::New (isolate_, context_);
Context::Scope context_scope (context);
Handle <String> source = String::NewFromUtf8 (isolate_, js . utf8 ());
Handle <Script> script = Script::Compile (source);
Handle <Value> result = script -> Run ();
I want to call this method over & over again, and each time, I want the context to contain any accumulated state from earlier calls. So if the code file contains (only) var x = 5; at the REPL I should be able to type > x and see the result 5.
But the actual result is x is not defined.

It turns out that this code actually does work as expected. The problem was that I was using browserify before running the code, and the code (e.g. var x = 5;) was getting wrapped into a function scope.

Related

Cypress how to store values yielded by a function into a variable

This has been bugging me from a long time. I am not well versed with javascript. Here it goes:
How do i store return value of a function into a variable:
lenValue = cy.get(selector).children().length
Above line of code returns undefined But when i try following in cypress test runner console then I get a valid output:
cy.$$(selector).children().length --> gives me correct number
How to return value from inside a then function and catch it to reuse later:
file1.js
function a(selector, attrName){
cy.get(selector).then(function ($el){
return $el.attr(attrName));
}
file2.js
state = file1Obj.a('#name','name')
What you're doing makes complete sense, but simply put, you cannot. (per the docs).
https://docs.cypress.io/guides/core-concepts/variables-and-aliases/#Return-Values
You can, however, use aliases to accomplish what (I think) you're after.
https://docs.cypress.io/guides/core-concepts/variables-and-aliases/#Aliases
#aeischeid shows you the wrong way to do it.
His code works only for a static site, but web pages are rarely static. As soon as API fetches are involved, lucky timing goes out the window and the test bombs.
This is why Cypress commands have automatic retry. Otherwise we could just build tests with jQuery.
Since cy.$$(selector).children().length --> gives me correct number, use that inside the helper function.
function a(selector, attrName) {
return cy.$$(selector).attr(attrName); // jQuery methods used
}
Or
function a(selector, attrName) {
return Cypress.$(selector).attr(attrName); // jQuery methods used
}
But be aware that jQuery only handles static pages, it does not retry if the attribute that you want to query arrives slowly.
For that use a command
cy.get('#name')
.should('have.attr', 'name') // retries until name exists
.then(name => { // guaranteed to have a value
// use name here
})
Here is a example from a cypress test I have that seems pretty relevant
let oldDescription;
cy.get('input#description').should(($input) => {
oldDescription = $input.val();
});
let randomDescription = Math.random().toString(36).substring(7);
cy.get('input#description').clear().type(randomDescription);
cy.get('input#description')
.parents('.ant-table-row')
.contains('Save').click();
cy.get('input#description').should('not.exist');
cy.contains(`${randomDescription}`);
cy.contains(`${oldDescription}`).should('not.exist');
because oldDescription is set inside of an asyncronous callback it isn't safe to expect it to be set, farther down the code outside of that callback, but in a lot of cases with cypress you end up having some other .get call or thing that waits, effectively pausing the code long enough that you can get away with not worrying about it.

V8 console.log does not print

I am attempting to embed v8 into my application, I am messing about seeing what is included in the V8 environment (duktape does not include a console implementation) and it seems like v8 does include an implementation however when I call console.log it does not print anything, instead it just prints undefined (which i assume to be the return value of console.log) So how would one go about linking the default std::cout output with console.log.
This is my code currently, I am working with the default hello world code very slightly modified.
int main(int argc, char* argv[]) {
// Initialize V8.
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
// Create a new Isolate and make it the current one.
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
{
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8(isolate, R"(
console.log("does not print?")
)",
v8::NewStringType::kNormal)
.ToLocalChecked();
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
}
}
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
std::cin.get();
return 0;
}
and I am using the prebuilt v8 binaries here
Try the following:
#include "src/debug/interface-types.h"
define your own "console delegate" class, deriving from debug::ConsoleDelegate
override any methods you're interested in, e.g. void Log(const debug::ConsoleCallArguments& args, const v8::debug::ConsoleContext&) override;
instantiate it and call debug::SetConsoleDelegate(isolate, &your_console_delegate); after creating your Isolate
To see an example, start at https://cs.chromium.org/chromium/src/v8/src/d8/d8-console.h?l=14&gsn=D8Console and trace where it's used.
So for anyone in the future that is dealing with this, this is the process I used to fix it.
download the source from here, only the src folder is needed.
extract it and link it in to your project where ever you put vendor code in addition to the bundle.
put it in the a src folder because otherwise its includes don't work
you will need to make a bunch of include directories for it to compile, mine include v8/src, and v8
make sure to link it with the nuget package, you may not have to do this, one machine needed it the other didn't.
you do not need to generate builtins-generated/bytecodes-builtins-list.h

How do you modify a nodejs module variable?

(This is probably a very silly question since I'm just beginning with nodejs, nevertheless I can't understand how this works. Let me know what is missing in my question, I'll correct.)
I'm trying to use the npm package likely.
in my server.js file I have thus written this
var Recommender = require('likely');
in likely.js you can find variables like these:
var DESCENT_STEPS = 5000; // number of iterations to execute gradient descent
var ALPHA = 0.0005; // learning rate, should be small
I would like to modify these variables inside my server.js file.
I believe the way to do that is adding this after the require()
Recommender.DESCENT_STEPS = 9999999999;
but that doesn't seem to change the value that is defined in likely.js and that is actually used by the model. (by running the model I can see it doesn't work since so much steps should take forever and the processing time doesn't change at all)
Can I only do this by modifying likely.js?
You cannot modify them programmatically because likely.js only uses the local variable values instead of the current value of the exported versions of the same variables. So if you wanted to change those values you currently would need to edit likely.js. You might want to submit a pull request to that project's repository that makes the code use the exported value (e.g. module.exports.DESCENT_STEPS) instead.
You need to publicize these variables to be viewable by server.js.
var object = {
DESCENT_STEPS = 5000;
ALPHA = 0.0005;
}
module.exports = object;
Now it can be viewed and modified in server.js.
Recommender.ALPHA = 'new value';

Namespace import in node.js

I've got some function that allows to merge namespace, very similar to import when the module contains lot's of function (I expose an API with dozens of combinators)
It generates lots of var f = target.f; for every item from the export
function getNamespace(name, exports){
var output='';
for(var item in exports){
output += 'var ' + item + ' = '+name+ '.'+item + ';';
}
return output;
}
and usage:
var paco = require('./paco.js');
eval(paco.getNamespace('paco', paco));
// instead of paco.between(paco.start(),paco.content(),paco.end())
between(start(), content(), end())
Question:
I there a way to 'hide' the eval into the some function ? I don't want neither to mutate global namespace nor to call vm.runInThisContext, just need to add some local variables into the calling context after call function similar to require.
I mean I need something like
import('./paco');
// this should work like this
// var paco = require('./paco.js');
// var between = paco.between;
but without mutation of global and without eval in the calling scope.
tl;dr: No.
In order to understand why this is impossible, it's important to understand what Node is doing behind the scenes.
Let's say we define a function in test.js:
function foo() {
var msg = 'Hello world';
console.log(msg);
}
In traditional browser JavaScript, simply putting that function declaration in a file and pulling the file in with a <script> tag would cause foo to be declared in the global scope.
Node does things differently when you require() a file.
First, it determines exactly which file should be loaded based on a somewhat complex set of rules.
Assuming that the file is JS text (not a compiled C++ addon), Node's module loader calls fs.readFileSync to get the contents of the file.
The source text is wrapped in an anonymous function. test.js will end up actually looking like this:
(function (exports, require, module, __filename, __dirname) {
function foo() {
var msg = 'Hello world';
console.log(msg);
}
});
This should look familiar to anyone who has ever wrapped their own code in an anonymous function expression to keep variables from leaking into global scope in a browser. It should also start making sense how "magic" variables in Node work.
The module loader evals1 the source text from step 3 and then invokes the resulting anonymous function, passing in a fresh exports object. (See Module#_compile.)
1 - Really vm.runInThisContext, which is like eval except it does not have access to the caller's scope
After the anonymous wrapper function returns, the value of module.exports is cached internally and then returned by require. (Subsequent calls to require() return the cached value.)
As we can see, Node implements "modules" by simply wrapping a file's source code in an anonymous function. Thus, it is impossible to "import" functions into a module because JavaScript does not provide direct access to the execution context of a function – that is, the collection of a function's local variables.
In other words, there is no way for us to loop over the local variables of a function, nor is there a way for us to create local variables with arbitrary names like we can with properties of an object.
For example, with objects we can do things like:
var obj = { key: 'value' };
for (var k in obj) ...
obj[propertyNameDeterminedAtRuntime] = someValue;
But there is no object representing the local variables of a function, which would be necessary for us to copy the properties of an object (like the exports of a module) into the local scope of a function.
What you've done is generate code inside the current scope using eval. The generated code declares local variables using the var keyword, which is then injected into the scope where eval was called from.
There is no way to move the eval call out of your module because doing so would cause the injected code to be inserted into a different scope. Remember that JavaScript has static scope, so you're only able to access the scopes lexically containing your function.
The other workaround is to use with, but you should avoid with.
with (require('./paco.js')) {
between(start(), content(), end())
}
with should not be used for two reasons:
It absolutely kills performance because V8 cannot perform name lookup optimizations.
It is deprecated, and is forbidden in strict mode.
To be honest, I'd recommend that rather than doing something tricky with eval, do your future maintainers a favor and just follow the standard practice of assigning a module's exports to a local variable.
If you're typing it that often, make it a single-character name (or use a better editor).
According to this answer Global variables for node.js standard modules? there is global object the same as in browser there is window. So you can add key to that object
function getNamespace(exports) {
for(var item in exports){
global[item] = exports[item];
}
}
and use it as:
paco.getNamespace(paco);
no need for eval at all.
No. It's not possible to modify the local scope from an external module. Reason being, when eval is called in the external module, its context will be the external module, not the scope requiring the module.
In addition, vm.runInThisContext does not have access to the local scope, so that wont help you either.

Setting an environment variable in javascript

How can I set an environment variable in WSH jscript file that calls another program? Here's the reduced test case:
envtest.js
----------
var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST_ENV_VAR") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);
envtest.bat
-----------
set
pause
I expect to see TEST_ ENV _VAR in the list of variables, but it's not there. What's wrong?
edit:
If someone can produce a working code sample, I'll mark that as the correct answer. :)
The problem is not in your code, but it is in execution of the process. The complete system variables are assigned to the process which is executed. so, your child process also had the same set of variables.
Your code-sample works good. It adds the variable to the SYSTEM environment.
So, you need to set the variable not only for your system but also for your process.
Here's the code.
var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST1") = "TEST_VALUE";
var oSysEnv = oShell.Environment("PROCESS");
oSysEnv("TEST1") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);
Once you created the system variable.
It will assign the newly created variable for the current process. So, your child process can get that variable while the "SET" command executed.
Sorry for my bad-english.
There are 4 "collections" (System, User, Volatile, and Process) you probably want Process if you just need a child process to see the variable
You are getting the system environment variables. I suspect you simply don't have permission to modify them; you could try changing this to the user environment variables.
Also I don't know whether the argument to Environment() is case-sensitive or not. MS's documentation uses "System" instead of "SYSTEM". Might make a difference but I don't know for sure.

Categories

Resources