-
Notifications
You must be signed in to change notification settings - Fork 10
Samples
I will now demonstrate two basic examples on how we could execute something in Vanilla Javascript or NodeJS style code.
On the hosted instance, we use the vm2 sandbox open source project, because we run untrusted code, it is not enough to just put the code into an eval and run it.
// this is a sample function only to demonstrate basic demo of the functionality
// we will send this script to the remote instance and get the result
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function sampleCalls() {
return {
first: getRandomInt(3),
second: getRandomInt(1),
third: Math.random()
};
}
sampleCalls();This is an example taken from the MDN webpage for Math.random(). It should return three random numbers as one object at the end. We need to call the function at the end, so we execute that and get the results back.
var faker = require('faker');
function fakerData() {
var randomName = faker.name.findName(); // Rowan Nikolaus
var randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz
var randomCard = faker.helpers.createCard(); // random contact card containing many properties
return randomName + " => " + randomEmail + " => " + JSON.stringify(randomCard);
}
module.exports = fakerData();This example uses the package faker. For this to work correctly, you would need to install the faker package first on the Docker instance you are running. This can be done in the same folder as there is the package.json file there with the command npm install faker or yarn add faker. This simply returns fake data as the Name, email and Card data for sample usage if you want to have "real looking" data on some presentation.
In a similar manner, you can use basically any NodeJS package in your scripts. Of course you have to consider implications because you run a remote instance, so it may not be a one-to-one experience for running this NodeJS vm and a real NodeJS application.
Servicenow x NodeJS @ 2019