I'm having issues with node.js, I'm not that familiar with it.
I have a JavaScript file that I need to load the file into node.js by using .load "filename.js".
when I run the command I just get a print out of the code that is in the file.
here is my code for the file I'm trying to load. I have made the changes suggested to me. but I'm still getting an entire print out of code.
class ArithmeticTaskRunner
{
constructor()
{
this.tasks = [];
}
addNegationTask()
{
const negationTask = (x) => -x;
this.tasks.push(negationTask)
return this;
}
addAdditionTask(y)
{
const additionByY = (x) => x + y;
this.tasks.push(additionByY)
return this;
}
addMultiplicationTask(y)
{
const multiplyByY = (x) => x * y;
this.tasks.push(multiplyByY)
return this;
}
taskCount()
{
return this.tasks.length;
}
execute(n)
{
let currentResult = n;
for(let task of this.tasks)
{
currentResult = task(currentResult)
}
return currentResult;
}
}
let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(10)
taskRunner.addNegationTask()
taskRunner.addMultiplicationTask()
taskRunner.execute(2)
here are examples of the output and the input that is needed on this task
1.
let taskRunner = new ArithmeticTaskRunner()
undefined
taskRunner.addAdditionTask(2)
undefined
taskRunner.addMultiplicationTask(4)
undefined
taskRunner.addAdditionTask(10)
undefined
taskRunner.execute(2)
26
taskRunner.execute(-2)
10
2.
taskRunner.execute()
-5
taskRunner.execute(10)
-10
taskRunner.taskCount
3
If you want to have a REPL session and run the commands in command line you can use repl module.
const repl = require('repl');
class ArithmeticTaskRunner {
... // Your class definition
}
// This starts the REPL session with the ArithmeticTaskRunner defined
repl.start().context.ArithmeticTaskRunner = ArithmeticTaskRunner;
Then in terminal:
node filename.js
And when you have node running:
let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(2)
taskRunner.addMultiplicationTask(4)
taskRunner.addAdditionTask(10)
taskRunner.execute(2)
taskRunner.execute(-2)
If you want to run the code completely and output the result use console.log in the code and run node filename.js:
class ArithmeticTaskRunner {
... // Your class definition
}
let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(2)
taskRunner.addMultiplicationTask(4)
taskRunner.addAdditionTask(10)
console.log(taskRunner.execute(2))
console.log(taskRunner.execute(-2))
In terminal:
node filename.js
I'm assuming you've done basically the following on the command line:
node
.load ArithmeticTaskRunner.js
The reason you're only seeing the code printed out is because you just have a class definition. You don't have an instance of TaskRunner. If that's your intent, at the bottom of your code add something like this:
const taskRunner = new TaskRunner();
console.log(taskRunner);
Then when you try those command line steps again, it will print out an instance of TaskRunner with your methods on it.
However, the entire purpose of the .load command is to put your script into the Node.js REPL. Alternatively you can instead do the following in the command line:
node
.load ArithmeticTaskRunner.js
const taskRunner = new TaskRunner();
console.log(taskRunner);
This will let you do work on the command line without hard-coding it into your script.
Update
If your intent is to execute the code without printing it out, you can do the following:
node ArithmeticTaskRunner.js
But you won't be making your code available to the global instance. You'd have to add code into that script that creates a 'TaskRunner` instance and make use of it, like I did initially and save it into that file.
class ArithmeticTaskRunner
{
constructor()
{
this.tasks = [];
}
addNegationTask()
{
const negationTask = (x) => -x;
this.tasks.push(negationTask)
return this;
}
addAdditionTask(y)
{
const additionByY = (x) => x + y;
this.tasks.push(additionByY)
return this;
}
addMultiplicationTask(y)
{
const multiplyByY = (x) => x * y;
this.tasks.push(multiplyByY)
return this;
}
taskCount()
{
return this.tasks.length;
}
execute(n)
{
let currentResult = n;
for(let task of this.tasks)
{
currentResult = task(currentResult)
}
return currentResult;
}
}
const arithmeticTaskRunner = new ArithmeticTaskRunner ();
console.log(arithmeticTaskRunner );
After this then try doing the steps on the command line:
node
.load ArithmeticTaskRunner.js
Update 2
This should open the Node REPL (leading '>` should appear). Afterwards do these commands one line at a time:
let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(2)
taskRunner.addMultiplicationTask(4)
taskRunner.addAdditionTask(10)
taskRunner.execute(2)
This should print 26.
taskRunner.execute(-2)
This should print 10.
Related
I'm writing a VS Code extension in JavaScript. It requires a loop to open several text files so I used a for loop. Here's my a sample of the code for the loop:
const allFiles = vscode.workspace.findFiles('**/*.*', '**/node_modules/**');
for (let i = 0; i < allFiles.length; i++) {
vscode.workspace.openTextDocument(allFiles[i])
}
Here's the whole extension.js file:
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const path = require('path')
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
/**
* #param {vscode.ExtensionContext} context
*/
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "code-runner-from-the-web" is now active!');
const allFiles = vscode.workspace.findFiles('**/*.*', '**/node_modules/**');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('code-runner-from-the-web.helloWorld', function () {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World from Code Runner From The Web!');
});
for (let i = 0; i < allFiles.legnth; i++) {
console.log (vscode.workspace.openTextDocument(allFiles[i]))
vscode.commands.executeCommand('code-runner.run', null)
}
context.subscriptions.push(disposable);
}
// This method is called when your extension is deactivated
function deactivate() {}
module.exports = {
activate,
deactivate
}
Where am I going wrong here?
The solution was to use an async function.
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const path = require('path')
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
/**
* #param {vscode.ExtensionContext} context
*/
async function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "code-runner-from-the-web" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('code-runner-from-the-web.helloWorld', function () {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World from Code Runner From The Web!');
const getAllFiles = vscode.workspace.findFiles('**/*.*', '**/node_modules/**');
const findFile = async () => {
const allFiles = await getAllFiles
console.log(allFiles)
for (let i = 0; i < allFiles.length; i++) {
vscode.workspace.openTextDocument(allFiles[i])
//vscode.commands.executeCommand('code-runner.run', null)
console.log("Hello!!!!")
}
}
findFile()
});
context.subscriptions.push(disposable);
}
// This method is called when your extension is deactivated
function deactivate() { }
module.exports = {
activate,
deactivate
}
You have a typo in the for loop. Instead of allFiles.legnth, it should be allFiles.length. The corrected code should be:
for (let i = 0; i < allFiles.length; i++) {
console.log (vscode.workspace.openTextDocument(allFiles[i]))
vscode.commands.executeCommand('code-runner.run', null)
}
I have some code in a web worker that is working perfectly locally, but as soon as I build and deploy (which minifies the code) it no longer works.
The unminified code looks like this:
const mapSourceCode = (treeNode, mfi, {objectType, types, fileType, templateType}) => {
let sourceCodeMap = new Map();
let ownerMap = new Map();
let sourceCodeList = [];
let ownerList = [];
let mfiMap = new Map();
mfi.forEach(row => mfiMap.set(row.uuid, row));
let sourceCodeObjects = mfi.filter(row => types.includes(row.objectTypeUuid));
if(sourceCodeObjects.length < 1)
return {sourceCodeMap, sourceCodeTree: undefined};
try {
sourceCodeObjects.forEach(sourceObj => {
let owner = findOwner(sourceObj, sourceObj, mfiMap, {...treeNode.data}, objectType);
The minified code is this:
i = function(e, t, n) {
var c = n.objectType
, o = n.types
, i = n.fileType
, u = n.templateType
, l = new Map
, s = new Map
, f = []
, p = []
, m = new Map;
t.forEach((function(e) {
return m.set(e.uuid, e)
}
));
var h = t.filter((function(e) {
return o.includes(e.objectTypeUuid)
}
));
if (h.length < 1)
return {
sourceCodeMap: l,
sourceCodeTree: void 0
};
try {
if (h.forEach((function(n) {
var r = a(n, n, m, Object(d.a)({}, e.data), c);
The line it's erroring out on is {...treeNode.data} on the last line.
The error is ReferenceError: d is not defined
I can't figure out what the issue could be? Like I said everything runs great on locally. Any help is greatly appreciated
I found the issue, in case anybody runs into this same thing.
Normally when using web workers you need to tell your builder (webpack) to build / compile workers separately. I'm using the default create-react-app configuration which doesn't give access to that part of webpack. unless you eject from create-react-app completely (which I'm currently not ready to do)
I'm using the react hook called useWorker, where I pass the function I want to allocate to the worker.
When your code is optimized and minified variable names are replaced with smaller names (mostly 1 or 2 letters from what I've seen). Because I didn't have any custom loaders to load my worker code, it used variables from the global scope assuming it would have access. When the code was extracted to a separate thread outside the main thread it no longer had access to those variables and thus didn't work.
The fix is to
Add a loader (you can either eject from create-react-app, or there may be some npm libraries that will give you access to that particular part of webpack)
Or my solution was to create the function in a string and create a function using the Function constructor like so
const generateFunction = new Function('treeNode', 'mfi', 'types', 'action', generateFunctionString);
Where the generateFunctionString was a string like: "return a + b"
I then passed that function into my useWorker hook:
const [generatorWorker] = useWorker(generateFunction);
Just like from IPython import embed; embed() but for node.
I want to open a REPL shell programmatically and be able to at least read the local variables. Being able to change them as well is a plus.
As far I know, the closest you can get is by using the repl built-in module (which is used by node inspect itself):
// ... your code you want to debug
const repl = require("repl");
const replServer = repl.start({
prompt: "Your Own Repl > ",
useGlobal: true
});
// Expose variables
const localVar = 42
replServer.context.localVar = localVar;
By running node index.js (assuming you saved the above content in index.js) we get access to this custom repl:
$ node index.js
Your Own Repl > localVar
42
Your Own Repl >
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
Your Own Repl >
However, this does not work like a debugger tool, but really, it's only a REPL.
You can build a REPL similar to the built-in Deno REPL and and evaluate expressions using the dangerous eval function. Through it you'll be able to access local variables and other things (e.g. window).
repl.ts
import { readLines, writeAll } from "https://deno.land/std#0.106.0/io/mod.ts";
export default async function repl(evaluate: (x: string) => unknown) {
await writeOutput("exit using ctrl+d or close()\n");
await writeOutput("> ");
for await (const input of readInputs()) {
try {
const value = evaluate(input);
const output = `${Deno.inspect(value, { colors: !Deno.noColor })}\n`;
await writeOutput(output);
await writeOutput("> ");
} catch (error) {
await writeError(error);
}
}
}
async function* readInputs(): AsyncIterableIterator<string> {
yield* readLines(Deno.stdin);
}
async function writeOutput(output: string) {
await writeAll(Deno.stdout, new TextEncoder().encode(output));
}
async function writeError(error: unknown) {
await writeAll(Deno.stderr, new TextEncoder().encode(`Uncaught ${error}\n`));
}
repl_demo.ts
import repl from "./repl.ts";
let a = 1;
let b = 2;
let c = 3;
await repl((x) => eval(x));
example usage
% deno run repl_demo.ts
exit using ctrl+d or close()
> a
1
> a = 40
40
> a + b
42
For deno (Title says Node.js, tag deno) you can use Deno.run to execute deno and write to stdin and read from stdout.
The following will do:
const p = Deno.run({
cmd: ["deno"],
stdin: "piped",
stdout: "piped",
stderr: "piped"
});
async function read(waitForMessage) {
const reader = Deno.iter(p.stdout)
let res = '';
for await(const chunk of reader) {
res += new TextDecoder().decode(chunk);
console.log('Chunk', res, '---')
// improve this, you should wait until the last chunk
// is read in case of a command resulting in a big output
if(!waitForMessage)
return res;
else if(res.includes(waitForMessage))
return res;
}
}
async function writeCommand(command) {
const msg = new TextEncoder().encode(command + '\n');
console.log('Command: ', command)
const readPromise = read();
// write command
await p.stdin.write(msg);
// Wait for output
const value = await readPromise
return value;
}
// Wait for initial output:
// Deno 1.0.0
// exit using ctrl+d or close()
await read('ctrl+d or close()');
await writeCommand('let x = 5;')
let value = await writeCommand('x') // read x
console.log('Value: ', value)
await writeCommand('x = 6;')
value = await writeCommand('x') // read x
console.log('Value: ', value)
If you run that snippet, the output will be:
Command: let x = 5;
Command: x
Value: 5
Command: x = 6;
Command: x
Value: 6
There are some improvements to be made, such as handling stderr but you get the idea.
This feature doesn't currently exist but is being proposed in https://github.com/denoland/deno/issues/7938.
The vision being something along the lines of
Deno.eval("Deno.repl()")
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
//to be sure this context is here
const ev = eval.bind(this);
function ask() {
rl.question('>', (code) => {
console.log(ev(code));
ask();
});
}
ask();
this code ask a input with readLine module and every time a reponse is provided the code is executed and a new input is askef
I am building a simple command line app in node using commander js. The problem is, when I run a particular command, it outputs the result of an other command as well.
I've tried multiple things but nothing seems to be working out.
I have two crawler objects as below in crawler.js file
var f = new Crawler({
//code here
});
var c = new Crawler({
//code here
});
c.queue("http://www.someurl.com")
f.queue("http://www.someurl.com")
module.exports = {
c,
f
};
My index.js file looks like this
const x =() => {
crawler.c;
}
const y =() => {
crawler.f
}
program
.command("x")
.action(()=>{
x();
});
program
.command("y")
.action(()=>{
y();
});
Whenever I call the command x, it fires y as well and vice versa.
I need to show command specific outputs. Please help.
I'm using something similar to NodeJS called bondi, it's build on the Firefox js engine.. Basically i'm getting this error and I believe it's due to the way i'm referencing "this" in the .Get function below.
Basically there is a tool called SFtpClient. It has the method of "Get", to list the contents of a folder, but I want to change the prototype for this with a drop in include file. I need to change it so that it
a/ retries several times when it fails, and b/ it has a recursive folder listing function.
So I used the prototype to change it - moved .Get to ._Get.
Can anyone see why I would be getting the error:
Jan 23 04:51:34 beta bondi: === this._Get is not a function --- Prio(6) Result(0x0) File(/home/nwo/approot/include/sftpclientenh
when I run the code below?
Thanks
SFtpClient.prototype._Get = SFtpClient.prototype.Get;
SFtpClient.prototype.Get = function(Folder, Retries){
//defaults
if(!Retries) Retries = 5;
if(!Folder) Folder = "~/";
//vars
var FileListing = [];
var connect = function(){
//TODO JRF 19.01.2012 : re-enable this when bondi is fixed
// this.HomeDirectory.replace(/\/?$/, "/");
FileListing = this._Get(Folder);
return true;
}
var i = 1;
do{
var res = false;
try {
res = connect();
}catch(e){
Debug.LogInfo(e.message);
}
i++;
Server.Sleep(i*2000);
} while(res==false && i < Retries);
return FileListing;
}
Try res = connect.call(this) instead of res = connect().