node-webkit 开机自启动
2014-08-11 · 373 chars · 2 min read
node-webkit 没有提供开机自启动的接口,在 github 的issue里也没有找到靠谱的解决方法,不过经过一番寻觅,找到了 node 下操作注册表的方法,就是winreg(这么好的项目星星少的可怜),还有一个使用 winreg 修改注册表实现开机启动的 demo:node-start-on-windows-boot。demo 很简单,可以直接在项目里使用:
文件 startOnBoot.js:
var WinReg = require('winreg')
var startOnBoot = {
enableAutoStart: function (name, file, callback) {
var key = getKey()
key.set(name, WinReg.REG_SZ, file, callback || noop)
},
disableAutoStart: function (name, callback) {
var key = getKey()
key.remove(name, callback || noop)
},
getAutoStartValue: function (name, callback) {
var key = getKey()
key.get(name, function (error, result) {
if (result) {
callback(result.value)
} else {
callback(null, error)
}
})
},
}
var RUN_LOCATION = '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
function getKey() {
return new WinReg({
hive: WinReg.HKCU, //CurrentUser,
key: RUN_LOCATION,
})
}
function noop() {}
module.exports = startOnBoot
使用:
var startOnBoot = require('startOnBoot.js')
//设置开机启动
startOnBoot.enableAutoStart('<写入注册表的key>', process.execPath)
//取消开机启动
startOnBoot.disableAutoStart('<写入注册表的key>')
这里有一点要注意,就是process.execPath :使用process.cwd() 获取当前目录是错误的,因为 node-webkit 在执行的时候,会将所有源码释放到一个临时目录(名字随机的),如下图:
这些都是临时目录,所以process.cwd() 会临时目录的地址,使用process.execPath 才能会的 exe 文件执行的路径。另外,如果使用 inno setup 打包的话,卸载时需要删除注册表信息,参考这篇文章:http://keenwon.com/1317



