---
title: "nodejs 控制脚本"
author: "李俊良"
date: "2013-11-15T18:27:24Z"
tags: []
categories: ["Web前端"]
slug: "nodejs"
draft: false
lastmod: "2013-11-15T18:27:24Z"
id: 1975762
url: "https://frosh.iteye.com/blog/1975762"
---

```
/**
super.js
用于启动js服务
保证js服务停止后自动启动
并且加入日志记录
*/
var spawn = require('child_process').spawn,
	server = null;


function startServer(){
	console.log('restart server');
	server = spawn('node',['/data/pushserver/js/pushserver.js','>','push.log']);
	console.log('node js pid is '+server.pid);
    server.on('close',function(code,signal){
    	server.kill(signal);
    	server = startServer();
    });
    server.stdout.on('data',function(data){
   	console.log("push:"+data);
    });
    server.stderr.on('data',function(data){
   	console.log("pusherror:"+data);
    });
    server.on('error',function(code,signal){
    	server.kill(signal);
    	server = startServer();
    });
	return server;
};
```

 

 

```
/*start.sh*/

#! /bin/sh
nohup node /data/pushserver/js/super.js >> /data/pushserver/js/restart.log &

/*stop.sh*/

ps aux | grep "pushserver.js" | cut -c 9-15 | xargs kill -9
```