I'm just doing some testing with JavaScript language feature with no DOM manipulation. So I'm editing a js file and I'm wondering how to simply run it and show the console output? I installed the moll/vim-node plugin, but no idea how to run js code.
4 Answers
Per this vim wikia entry you could create a shell execution to new buffer script and then extend it to run your code using node.
command! -complete=shellcmd -nargs=+ Shell call s:RunShellCommand(<q-args>)
function! s:RunShellCommand(cmdline)
let isfirst = 1
let words = []
for word in split(a:cmdline)
if isfirst
let isfirst = 0 " don't change first word (shell command)
else
if word[0] =~ '\v[%#<]'
let word = expand(word)
endif
let word = shellescape(word, 1)
endif
call add(words, word)
endfor
let expanded_cmdline = join(words)
botright new
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
call setline(1, 'You entered: ' . a:cmdline)
call setline(2, 'Expanded to: ' . expanded_cmdline)
call append(line('$'), substitute(getline(2), '.', '=', 'g'))
silent execute '$read !'. expanded_cmdline
1
endfunction
command! -complete=file -nargs=* RunJS call s:RunShellCommand('node '.<q-args>)
Then if you run :RunJS %
you should get a new buffer with the output of your node.js execution. Optionally you can call things directly using :Shell <cmd>
I think Codi is what you are looking for. It supports JavaScript and some other languages.
No plugin required! You can run node with the shell command :!
Run the entire file with :!/usr/local/bin/node %
Run the current line with :exec '!/usr/local/bin/node' '-e' shellescape(getline('.'))
2021 Update
Later versions of Vim and NeoVim now have terminal support built-in. Use the :term(inal)
command to open a new terminal.
Original Answer
I highly recommend https://github.com/Shougo/vimshell.vim for this purpose.
Its a vim plugin that allows you to run a terminal within vim. You can open the terminal in a new tab with
:VimShellTab
or quickfix window with
:VimShellPop
then you can run commands as usual, i.e.
node
:!node %
. This will shell out to the externalnode
program, passing the current filename as an argument. Output will be displayed on the screen, and you can press Enter to dismiss it.