在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. }