skip to Main Content

Here’s my keybinding:

{
    "key": "alt+enter",
    "command": "workbench.action.terminal.runActiveFile",
    "when": "editorTextFocus && !editorHasSelection && resourceLangId == 'javascript'",
    "args": { "text": "node ${file}" }
}

I am currently learning JavaScript. I used to run Alt+Enter to execute whatever code I had. I tried to add a keybinding, but it seems that it’s not accepting the arguments, and it prints the file directory only. Do you have any ideas on how to solve this issue?

I’m expecting to be able to execute the active JS file in the terminal.

2

Answers


  1. If You Want to know How to run a JavaScript file in Visual Studio Code

    There are two ways to run a JavaScript file in Visual Studio Code:

    1. Use the command palette:

      • Press Ctrl+Shift+P to open the command palette.
      • Type Run JavaScript File and select the workbench.action.terminal.runActiveFile command.
    2. Use the keyboard shortcut:

      • By default, the keyboard shortcut for running the active file is Ctrl+F5.
      • You can customize the keyboard shortcut by going to File > Preferences > Keyboard Shortcuts and searching for workbench.action.terminal.runActiveFile.

    If you are using the keyboard shortcut, make sure that the active editor is a JavaScript file. You can check this by looking at the file extension in the bottom right corner of the window. The file extension should be .js or .cjs.

    Once you have run the JavaScript file, the terminal will be opened and the node ${file} command will be executed. This will start the Node.js runtime and run the JavaScript file.

    If you are new to Visual Studio Code or JavaScript, I recommend that you start by running a simple JavaScript file. For example, you could create a file called hello_world.js and add the following code:

    console.log("Hello, world!");
    

    Then, you could run the file using one of the methods described above. When you run the file, you should see the following output in the terminal:

    Hello, world!
    
    Login or Signup to reply.
  2. I don’t think runActiveFile accepts arguments like that. It just runs the file by its path in the terminal. You need to add a shebang unless you want the file to be interpreted by your platform’s default interpreter (Ex. system shell). For NodeJS, that’d be something like #!/usr/bin/env node. And you’d need to give execute permissions for the file (Ex. chmod +x or your platform’s equivalent).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search