Toggle Node Build Window on Sublime Text 2 - javascript

I would like to be able to use one shortcut for running and killing node process including showing and hiding build window as needed.
I press ctrl + B:
Show Build Window
Run Node process
I press ctrl + B again:
Kill Node process
Close Build Window.
I also need kill signal to be sent so that I can read it in node application and perform couple of actions prior to the exiting.
Currently the first part of what I need is working but to close node app I need to ctrl + shift + B and then hit esc to close build window.
Is this possible and if it is, how?
EDIT 1 (18.09.14)
Made a sublime text plugin that does exactly what I described above. Currently tested on ST3 (Windows and Linux). Only issue currently is that on windows platform, your node script wont get proper kill signal (SIGINT or something similar) for pre-exit proecedures. I use sublime texts own console for io procedures - very convenient. Might release plugin soon if people feel interested in it.

One approach would be to, in your build system, first kill the running node process & if that's not successful pass the current file to node. So your node.sublime-build might look like this:
{
"cmd": [ "killall node || node \"$file\"" ],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.js",
"shell": true
}
Sublime only allows one command which is passed multiple arguments, so something like "cmd": [ "killall node ||", "node", "$file"] wasn't working, though I think it worked previously in Sublime 2. Thus the need to wrap $file in escaped quotes, because otherwise the command will fail if the path to $file has a space in it. Also, || is pivotal here, because killall exits with a status of 1 (error) if there were no processes to kill, so the first time it will run node but the second time it won't.
Note that, since we're working in the shell here, this is platform-specific. I don't know how to do the equivalent of || on Windows, but you'd just need something like this:
{
"cmd": [ "killall node || node \"$file\"" ],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.js",
"shell": true
"windows": {
"cmd": [ "insert whatever works here..." ]
}
}
One big limitation is that this kills all running node processes; that'd be annoying if you want to keep something running in the background. If someone knows how to target a specific node process in a single command, please add to my answer.
Secondly, you could wrap the cmd in a bash script, which would make it easier to do multiple things like kill a particular process. Then the cmd array would be [ "bash", "name-of-script.sh" ]. Using lsof it would be rather easy to get the particular node process that's running your current file. You could also use bash -c as the command and then paste a whole script into the second element of the cmd array.
Hope that helps. I'm missing one piece of your requirement: ESC will still be needed to close the build window. Not sure what else can be done there without writing a Sublime plug-in.

Anyway, I fix it in windows like that
{
"shell": true,
"windows": {
"cmd": "(TASKKILL /F /IM node.exe || 1)&& node \"$file\""
}
}

I did it the same way but not checking for any file other than .js files
{
"cmd": [ "killall node || node \"$file\"" ],
"selector": "*.js",
"shell": true
"windows": {
"cmd": "(TASKKILL /F /IM node.exe || 1)&& node \"$file\""
}
}
This will kill any running node and restart the file whose tab is open

Related

When printing Node command line arguments, why are forward slashes being removed?

In a Node command I have passed two arguments--each a file name. When I print the command line arguments to the console using the console.log(process.argv), the last argument is missing the slash delimiters in the path. Any ideas why, or how to troubleshoot this? Here is the output.
[
'C:\\Program Files\\nodejs\\node.exe',
'c:\\Users\\66851\\development\\projectb\\file-changed.js',
'c:Users66851developmentprojectbtest-file.js'
]
Details
The details are that the Node command is actually a command that is run by a VSCode extension: Run on Save, which executes a file (file-changed.js) containing the aforementioned console.log command. I've posted this issue at their GitHub repo, but there has been no reply. The Run on Save settings in this case are:
"emeraldwalk.runonsave": {
"shell": "C:/Program Files/Git/bin/bash.exe",
"commands": [
{
"cmd": "node file-changed.js ${file}"
},
]
},
Of Note
I have a separate Node project, configured identically with the Run on Save extension. In that project this issue is not present.
I figured out the cause of my issue. It was due to this line in my settings.json file:
"shell": "C:/Program Files/Git/bin/bash.exe",
Once I removed that, my issue went away.

Setting an env var in package.json for use with electron-reload?

I usually develop on macOS but I've moved the project over to Windows 10 in order to work on some Windows-specific issues. I use electron-reload to reload the app when changes are made. It's been working wonderfully on macOS but breaks on Windows.
Using the setup below, and npm start to start the app, on Windows it throws an error: "'APP__DEV' is not recognized as an internal or external command"
Am I doing this wrong and macOS is just more "forgiving"? I saw this question: Setting process.env var in package.json and the accepted answer looks the same as what I am doing so I'm confused.
Before I jump down the rabbit hole, I thought I would ask if there is something simple wrong with what I am doing.
If it matters – I didn't do any conversion of CTLF, etc when moving the project to Windows – I just copied it over using DropBox.
package.json
"start": "APP_DEV=true electron .",
Main.js
let isDev = process.env.APP_DEV ? (process.env.APP_DEV.trim() == "true") : false;
if (isDev) {
require('electron-reload')(__dirname);
}
The syntax ENV_VAR=value program arguments is a UNIX thing. Windows does not provide a way to set an environment variable and run a program in the same command, however, this will generally work: set ENV_VAR=value && program arguments (so, in your case: set APP_DEV=true && electron . is what you're looking for). As a suggestion, look at dotenv and/or cross-os to make your project more usable (in this regard) on all systems without too much headache.
Have you tried moving your argument till after the electron command ("electron") and src location (".")?
APP_DEV does NOT exists:
"start": "APP_DEV=true electron ."
APP_DEV does exists:
"start": "electron . APP_DEV=true"
EDIT:
The above mentioned method would not be able to retrieve as enviromental variables, but as process arguments. Not sure if this will be able to solve your issue.
string[] argument = process.argv;

How to set up a conditional npm script based on the output of another?

This is an issue I have run into before when trying to set something up with npm scripts, yet I have not been able to solve it. Not even sure this is possible, preferably I would like the solution to work in both Mac and Windows environments.
I'm trying to split up some of the logic of my npm scripts into several short scripts that can call each other. This in combination with variables would make the scripts better maintainable and readable for other developers.
I can not figure out however how to use the result of one npm script in another. I'm hardly a bash expert so that why I'm looking for some help here (:
In this example I'm trying to set up a script which allows the developer to easily launch a docker (virtual) environment.
in the package.json:
...
"config": {
"docker": {
"container": "docker-test"
}
},
"scripts": {
"container_run": "docker run -d -p 80:80 $npm_package_config_docker_container"
"container_running": "docker inspect -f {{.State.Running}} $npm_package_config_docker_container || echo 'false'",
"container_stop": "docker stop $npm_package_config_docker_container && docker rm $npm_package_config_docker_container",
"start": "???"
}
So here I have a variable containing the name of a docker container to be run: $npm_package_config_docker_container.
When I do npm run container_running, this will return true, if the container is running or throw an error if the container is not there in which case it will echo 'false'. So far so good.
Now I would like the start script to check if the container if running, if so stop the container and start a new run and of it is not running just start a new run.
So something like this:
"start": "if [ container_running == "true" ]; then container_stop && container_run; else container_run; fi"
So the question is how to achieve this? And as a bonus question, can this be done in a way that is compatible in both Mac and Windows environments?
Any help would be much appreciated!!
After some more digging I found a solution to his although I'm sure this could be improved.
You can use command substitution to run $(npm run container_running), this will return all the output from running that command (in a subshell).
Then you can test the output to check if the last word was 'true'.
"start": "if [[ $(npm run container_running) == *true ]]; then npm run container_stop && npm run container_run; else npm run container_run; fi"
Have not tested this on Windows yet.
If anyone has a better idea / solution please let me know!
Honestly, for anything more complex than a single command with options, I create a bin folder and add a custom script file for it, then have one of the non scripts call that instead. E.g.:
"container_run": "./bin/container-run"
The thing is, you don't have to be a bash expert then because you can create that file with a #! /usr/env node at the top and then write the rest in JavaScript.

How to compile a TypeScript file from within the new Visual Studio Code on Mac OS X

Microsoft has just released the new Visual Studio Code for the Mac OS X platform. It supports TypeScript, in that one can get autocomplete and error reporting for TypeScript code.
My question: How can we compile a TypeScript file (to produce the corresponding JavaScript file) from within Visual Studio Code? I have created a default tsconfig.json file as recommended, with just {}, and have tried invoking shift+command+B but this does not produce an updated JavaScript file.
You will need to set up a task to do this.
I apologise in advance if I get the short-cuts a bit wrong as I am sat using a different operating system. For anyone using Windows, it will be CTRL - I think the OSX version just means using CMD instead.
If you press CTRL + SHIFT + P, you should get an action menu appear that allows you to search all commands.
Type Configure Task Runner. If you don't already have one, this will create a tasks.json file in a settings folder for you. Otherwise, it will open the existing tasks.json file.
You can uncomment the TypeScript task that is built in - it looks like this (my main file is app.ts, the default in this file is HelloWorld.ts):
// A task runner that calls the Typescipt compiler (tsc) and
// Compiles a HelloWorld.ts program
{
"version": "0.1.0",
// The command is tsc.
"command": "tsc",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Under windows use tsc.exe. This ensures we don't need a shell.
"windows": {
"command": "tsc.exe"
},
// args is the HelloWorld program to compile.
"args": ["app.ts"],
// use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
}
You can then this task on demand using CTRL + SHIFT + B.
If you have multiple tasks defined, you can use CTRL + E and type task (note the space after "task") and it will give you a list of all tasks for you to choose from.
Your hands don't need to leave the keyboard for any of this!
Lastly... if you are still getting nothing, check this icon at the bottom of the window as you may have a compiler error... (the icons below are showing one error - click on it in your editor for details).
I had faced the same issue with the tsc transpiler (since it compiles a source code from one format to another) not generating the ".js" file.
Workaround:
Try executing the following command in your Windows Command Prompt (cmd.exe - Run as Administrator):
tsc test.ts
Ensure that you are in the right folder path or else provide the absolute path for the ".ts" file
Hopefully, it should generate the ".js" file in the same folder as the ".ts" file.
Now that the ".js" file is generated, inorder to avoid executing the above command everytime you make a change, you can execute an auto-transpilation watch command in tsc.
To perform an auto-transpilation for the ".ts" file, try running the following command:
tsc test.ts --watch
Now if you go back to your ".ts" file and make changes and hit Save, it will perform an auto-transpilation and update your ".js" file instantly. Remember to keep the command prompt running.
I am yet to explore the reason as to why the tsc transpiler is not working on Visual Studio Code's Ctrl + Shift + B keypress, but my best guess would be an issue with the tsc version used by my Visual Studio Code installation or the environment PATH variables defined or npm installed a different tsc version.. reasons could be multiple.
Output:
But for those who want to get things done quickly, i hope this workaround helps.
You need a tsconfig.json file to define all options for the TypeScript Compiler, and a tasks.json file to set the compiler options.
tsconfig.json
{
"compilerOptions": {
"target": "ES5",
"module": "amd",
"sourceMap": false
}
}
tasks.json ... See the line "args" with ${file} to compile the opened file.
{
"version": "0.1.0",
// The command is tsc.
"command": "tsc",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Under windows use tsc.exe. This ensures we don't need a shell.
"windows": {
"command": "tsc.exe"
},
// args is the HelloWorld program to compile.
"args": ["${file}"],
// Use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
}
More info: http://blogs.msdn.com/b/typescript/archive/2015/04/30/using-typescript-in-visual-studio-code.aspx
I found a solution that worked on the Mac. In the args line, I put the full path name for the TypeScript file that I wanted to compile. Then, launching a build using CMD + SHIFT + B did successfully run the tsc compiler and did successfully generate the corresponding JavaScript file.

Using node-inspector with Grunt tasks

Does someone used node-inspector with Grunt for application debugging? If not, Can you recommend a debugging tool for Grunt based apps?
I'm working with nodejs for a server side app and I have Grunt to use separated tasks (this is because users can execute tasks separately).
To run grunt in debug, you need to pass the grunt script to node explicitly:
node-debug $(which grunt) task
and put a debugger; line in your task. node-inspector will then open a browser with debugging tools.
Edit 28 Feb 2014
node-inspector has added the command node-debug, which launches node in a --debug state and opens the browser to the node-inspector page, stopping when it hits the first debugger line or set breakpoint.
Edit 30 January 2015
On Windows, things are a touch more complicated. See the answer from #e.gluhotorenko for instructions.
Windows solution
Run
node --debug-brk c:\Users\username\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt taskname
from cmd in the directory with your Gruntfile.js. Do not forget to put debugger; line in necessary places.
To debug, we have to modify the grunt file under bin. On my machine, grunt is installed globally, so I went to /usr/local/lib/node_modules/grunt/bin
I opened the file and modified:
#!/usr/bin/env node
To
#!/usr/bin/env node --debug-brk
--debug-brk will break on the first line of javascript ran.
Doing that alone isn't quite enough though, since you won't be able to find you're grunt task js file in the drop down in node inspector, so you have to modify the file you're interested in debugging by adding debugger; where you want the breakpoint to happen.
Now you can click continue after the first break, and you'll break on you're debugger; line
Pretty kludgy, but it's the only way I've found so far.
I recently created grunt-node-inspector to easily configure node-inspector with the rest of your grunt workflow, check it out: https://github.com/ChrisWren/grunt-node-inspector
Here is a section of a Gruntfile which illustrates how you can debug a grunt task using grunt-node-inspector, grunt-concurrent, and grunt-shell: https://github.com/CabinJS/Cabin/blob/master/Gruntfile.js#L44-L77
I have done a task to run my app and launch node-inspector.
It is far better than current proposition, you just have to add this task in gruntfile:
grunt.registerTask('debug', 'My debug task.', function() {
var done = this.async();
grunt.util.spawn({
cmd: 'node',
args: ['--debug', 'app.js'],
opts: {
//cwd: current workin directory
}
},
function (error, result, code) {
if (error) {
grunt.log.write (result);
grunt.fail.fatal(error);
}
done();
});
grunt.log.writeln ('node started');
grunt.util.spawn({
cmd: 'node-inspector',
args: ['&'],
opts: {
//cwd: current workin directory
}
},
function (error, result, code) {
if (error) {
grunt.log.write (result);
grunt.fail.fatal(error);
}
done();
});
grunt.log.writeln ('inspector started');
});
Great answers here. In 2017, now you can do
node --inspect --debug-brk $(which grunt) taskName
Which prints something like.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/232652c3-f63c-4b00-8de9-17dfad5db471
Open that URL in chrome, and you're good to go!
I'm using Node 7.3.0 and I'm on Mac. You might have to follow some of the advice in other posts to get it going on Windows.
2019 update
If you want to launch the grunt task in debug mode and break at first line:
node --inspect-brk $(which grunt) taskName
If you want to launch the grunt task in debug mode at a specific port:
node --inspect-brk=8080 $(which grunt) taskName
if you want to attache VSCODE to the node process running the debugging session of grunt, use the following configuration in vscode:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach by port IP 5656",
"port": 8080
}
]
}

Categories

Resources