mowatermelon / studyNode

Learning record
MIT License
4 stars 1 forks source link

2018/5/3 #137

Open mowatermelon opened 6 years ago

mowatermelon commented 6 years ago

node 打开浏览器

npm install --save opn
const opn = require('opn');
// 使用默认浏览器打开
// opn('http://sindresorhus.com');
// 使用默认软件打开图片
opn('unicorn.jpg').then(() => {
    // image viewer closed
    console.log('opened')
});

// 制定浏览器打开
// opn('http://sindresorhus.com', { app: 'firefox' });

// Specify app arguments  隐身模式打开chrome 浏览器
// opn('http://sindresorhus.com', { app: ['chrome', '--incognito'] });

opn.js 核心代码

const childProcess = require('child_process');

const cp = childProcess.spawn(cmd, args, cpOpts);

详情部分可以查看node 模块 child_process 部分

mowatermelon commented 6 years ago

/**
 * 引入模块
 * @type {[type]}
 */
let fs   = require("fs");
let mime = require("mime");
let path = require("path");

/*******************************************************************************************/

/**
 * [Send 创建发送响应对象]
 */
function Send(){};
Send.prototype.cache={};//设置缓存变量,因为缓存变量比读取文件要快

/**
 * 错误404页面
 * @param  {[type]} res [description]
 * @return {[type]}     [description]
 */
Send.prototype.err404 = function(res){
    res.writeHead(404,{"Content-Type":"text/plain"});
    res.write("<h1>404</h1><p>file not found</p>");
    res.end();
};

/**
 * 正确访问页面
 * @param  {[type]} res         [description]
 * @param  {[type]} fileName    [description]
 * @param  {[type]} fileContent [description]
 * @return {[type]}             [description]
 */
Send.prototype.sendFile = function(res,fileName,fileContent){
    res.writeHead(200,{"Content-Type":mime.lookup(path.basename(fileName))});
    res.end(fileContent);

};

/**
 * 发送静态页面方法
 * @param  {[type]} res     [description]
 * @param  {[type]} absPath [description]
 * @return {[type]}         [description]
 */
Send.prototype.serveStatic = function(res,absPath){
    let _this=this;
    if(this.cache[absPath]){
        this.sendFile(res,absPath,this.cache[absPath]);
    }else{
        fs.exists(absPath,function(exists){
            if(exists){
                fs.readFile(absPath,function(err,data){
                    if(err){
                        _this.err404(res);
                    }else{
                        _this.sendFile(res,absPath,data);
                    }
                })
            }else{
                _this.err404(res);
            }
        })

    }
};

Send.prototype.staticDirectory=function(req,url){
    let filePath=false;
    if(new RegExp("^/"+url+"/.*").test(req.url)){
         filePath=url+req.url;
    }
    let absPath="./"+filePath;

    return absPath;

}

/*******************************************************************************************/

module.exports=Send;