在Sublime Text中可以很容易配置新的编译运行命令,下面的截图是汉化版的中文菜单,英文菜单请直接对照。

首先需要在本地安装Node,默认的Node会加入到系统的环境变量,这样执行Node命令时就不需要到安装路径下执行了。

技术分享

选择“新编译系统”,在打开文件中插入以下代码:

  1. {
  2. "cmd": ["node", "$file"],
  3. "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  4. "selector": "source.js",
  5. "shell":true,
  6. "encoding": "utf-8",
  7. "windows":
  8. {
  9. "cmd": ["node", "$file"]
  10. },
  11. "linux":
  12. {
  13. "cmd": ["killall node; node", "$file"]
  14. }
  15. }

保存为Node.sublime-build,以后想运行当前文件,直接使用快捷键“Ctrl+B”即可,上述这段代码是大部分网上教程分享的,但是这个配置有一个问题,在windows系统中,这样每Build一次就会新产生一个Node进程,占用1个端口,下次想重新Build时会提示端口被占用

  1. function logger(req,res,next){
  2. console.log(‘%s %s‘,req.method,req.url);
  3. next();
  4. }
  5. function hello(req,res){
  6. res.setHeader(‘Content-Type‘,‘text/plain‘);
  7. res.end(‘hello world‘);
  8. }
  9. var connect=require(‘connect‘);
  10. var app=connect();
  11. app.use(logger).use(hello).listen(3000);
例如上述的connect中间件程序中监听了3000端口,第一次Build时没有错误,但是第二次Build就会发生下面的错误。

技术分享

网上又有人给出了下面的配置来解决问题:

  1. {
  2. "cmd": ["node", "$file"],
  3. "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  4. "selector": "source.js",
  5. "shell":true,
  6. "encoding": "utf-8",
  7. "windows":
  8. {
  9. "cmd": ["taskkill /F /IM node.exe", ""],
  10. "cmd": ["node", "$file"]
  11. },
  12. "linux":
  13. {
  14. "cmd": ["killall node; node", "$file"]
  15. }
  16. }
这样配置的本意是在cmd命令前面加个kill node进程的命令,但是实际测试并没有起作用,最后我将第一行命令改成如下所示同时执行两个命令,在windows系统上就没出现上述问题了。

  1. {
  2. "cmd": "taskkill /F /IM node.exe & node \"$file\"",
  3. "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  4. "selector": "source.js",
  5. "shell":true,
  6. "encoding": "utf-8",
  7. }