Front end construction desktop-class music player (NW and ELECTRON)

Server addressmajunchang.cn:3000/#/recommend

Recently looking at how the front end constructs desktop-level applications, take a look at NW and Ecectron. So I used Vue to write a PC version of QQ music player. Because time is too tight, the function of doing is very limited. Code duplication is high. I hope you can understand. This article mainly introduces two tools nw and ELECTRON. The front-end code has been open source, interested students can download it, add some interesting functions and optimize the code

Attached – Use Promise for front-end caching (sample code in Recommend.vue)

interface

// Categorize playlist data

export function getDiscList() {
  let href = window.location.href
  let url
  if (href.includes('localhost') || href.includes('127.0.0.1')) {
    url = '/api/getDiscList'
  } else {
    url = 'http://127.0.0.1:3000/api/getDiscList'
  }

  // Data to be spliced
  const data = Object.assign({}, commonParams, {
    platform: 'yqq'.hostUin: 0.sin: 0.ein: 29.sortId: 5.needNewCode: 0.categoryId: 10000000.rnd: Math.random(),
    format: 'json'
  })

  return axios.get(url, {
    params: data
  })
}

Copy the code

The cache

import {
  getDiscList
} from './recommend.js'

let getDiscListCache
let test

function fn() {
  if(! getDiscListCache) { test ='Test variable'
    getDiscListCache = getDiscList() // Send the interface back end when this assignment import is introduced
  }
}
fn()

export {
  getDiscListCache,
  test
}

Copy the code

use

methods: {
    getcateList() {
      getDiscListCache.then(res= > {
        console.log(test);
        console.log(res);
        this.songList = res.data.data.list; }); }}Copy the code

Project Preview

Divided into home page, singer list page, singer details page, ranking. Leaderboard details page and player page, leaderboard and singer page are basically the same as do not repeat

Home page

Singer List page

Singer Details Page

Singer search function

Player page

Technology stack

  • Front-end VUE, VUE-Router, Webpack

  • Node + Express acts as a proxy

  • The interface forwards jSONP AXIos

  • Packing tool electron electronic-Packager

Project introduction

1. Data acquisition

Data is mainly access to QQ music interface, jSONP interface can be access to the data interface need to use Node to do a proxy to solve the cross domainCopy the code

2. Proxy forwarding

During development, we can use proxyTable in the Dev module of Vue for path rewriting and proxy forwarding. During build, we can manually configure the access path or use Express for configuration similar to how we put code into the Nginx serverCopy the code

3. Precautions for the project

We need to resolve cross-domain issues with the server node starts on (i.e. the local server). We need to resolve issues with the index. HTML and static resource paths when using NWCopy the code

4. Project optimization points

The CSS part of the project can be optimized to less, Components like sass or CSsmodule can be removed from the current chart details page and the artist details page. The logic is basically the same. You can remove and use componentize, you can use slotCopy the code

NodeJs + Express agent

A uses Express to access the static resources of the packaged dist directory

B To solve the problem of cross-domain access after the dist file is dragged into NW or opened in the dist directory index.html directly and using the interface after electron packing

import path from 'path'
import express from 'express'
import axios from 'axios'
import {join} from 'path'

const app = express()

// Mount the static path
// A
app.use(express.static(join(__dirname, '.. /.. /dist')))

let router = express.Router()

// B
router.all(The '*'.function (req, res, next) {
  // res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Origin'.The '*')
  res.header('Access-Control-Allow-Headers'.'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods'.'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By'.'3.2.1')
  next()
})

// Do proxy distribution and request classification playlists
router.get('/getDiscList'.function (req, res) {
  var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
  axios.get(url, {
    headers: {
      referer: 'https://c.y.qq.com/'.host: 'c.y.qq.com'
    },
    params: req.query
  }).then((response) = > {
    console.log('Interface responded successfully')
    res.json(response.data)
  }).catch((e) = > {
    console.log(e)
  })
})

router.get('/lyric'.function (req, res) {
  var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'

  axios.get(url, {
    headers: {
      referer: 'https://c.y.qq.com/'.host: 'c.y.qq.com'
    },
    params: req.query
  }).then((response) = > {
    // Since response is a JSONp format, we need to json convert this
    var result = response.data
    var regExe = /^\w+\(({[^()]+})\)$/
    var matchArr = result.match(regExe)
    if (matchArr) {
      res.json(JSON.parse(matchArr[1]))
    }
  }).catch((e) = > {
    console.log(e)
  })
})

app.use('/api', router)

app.listen(3000, () = > {console.log('Server started, listening for port 3000')})Copy the code

Nw (Introduction and Use of Node-weikit)

Node – its introduction

The official website needs to turn over the wall download need to turn over the wall (alas…… Post the front page of nw’s website and download screenshots here.)

Github’s Nw.js has over 20,000 stars and close to 3,000 forks, suggesting it’s quite mature. And at the very end of the Github project, Intel is sponsoring the project, which looks awesome

  • Nw.js is also a framework for building PC applications using front-end technologies (HTML, CSS, JavaScript).
  • It is compatible with Windows XP
  • Support HTML5, CSS3, JS and WebGL to write applications, both desktop and mobile;
  • Full support for Node.js APIs and all third-party modules;
  • Performance will not be poor, enough for lightweight applications;
  • It’s easy to package and distribute an application, which means you can write a single piece of code that can be easily ported to different platforms (including mainstream Linux, Mac OS X, and Windows).
What can NW do?

Nw.js is a program written with HTML, CSS, and JavaScript that originally runs in a browser, but can also run on the desktop.

Nw installation and use
  1. Download the installation package to install (it is recommended that you download the development package for easy debugging)

    Download the nw.app zip package from the official website and decompress it for use

The official website is github.com/nwjs/nw.js

Effect:Copy the code

  1. Use command line installation (command line download is slow so not particularly recommended)
sudo npm install -g nw
Copy the code
Nw’s packaging process

Packaging tools (a brief introduction to several)

  • Nodebob is a Node-WebKit build tool that automatically publishes Node-WebKit applications in Windows environments. Currently in V0.1, written with Windows batch script.
  • Nw-builder & Grunt – NW-Builder allows you to build Node-WebKit applications for MAC, Win, and Linux using Grunt. They will download the pre-built binary for a particular version, unzip it, create a version folder, create the app.nw file for the specified directory, and copy the app.nw file to where it belongs
  • Nuwk! Nuwk! You can easily create Mac applications based on Node-WebKit, simplifying the testing and build process. It is responsible for creating executable files, attaching application ICONS, and configuring plist files accordingly. (Very alpha stage)
  • Generator-node-webkit is a Yeoman generator for developing Node-WebKit applications and creating packages for MAC, Linux and Win. Loose integration into your build process will download NWJS 32/64bit for Linux, Windows, and OSX and build packages for all three platforms from a given source directory.

Under Windows packaging process of www.cnblogs.com/tinyphp/p/5…

Packaging process for MAC/OSX

Blog.csdn.net/weichuang_1…

Blog.csdn.net/baidu_30907…

Nw solves the problem of not playing audio

MP3 encoding belongs to patent encoding, not open source authorization, so in Nw.js does not support MP3 playback by default, you need to manually enable it.

You need to download the corresponding libffmpeg. DLL file from the community and replace it

Community Address: github.com/iteufel/nwj…

The target file address: / Users/baidu/Desktop/NWJS – SDK – v0.31.1 – osx – x64 / NWJS. App/Contents / / 67.0.3396.79 Versions

I’ve installed this software on my desktop and this is the target address and you just have to remember what’s behind it, the number after Versions stands for nw embedded Google version (it’s okay if it’s different)

How to use NW and how to debug

Use the shortcut option+ Command + I to open the built-in Google console. If it does not open or does not respond, it may be that the downloaded version does not come with development tools

The application of the nw

NWJS – You deserve it! It has to be noted that nw.js has developed applications that cover many areas:

  1. WhatsApp, the classic chat app, Messenger;
  2. Powder Player seed download, and video Player;
  3. The Boson Editor code Editor, and even a Markdown Editor called story-writer;
  4. Leanote Desktop App Is a note-taking App similar to Evernote.
  5. Mongo Management Studio database Management application.

Electron (Introduction and Use)

Official website address (not having to climb the wall is great)

electronjs.org/

Introduction to the

  • Electron is a framework that allows us to create desktop applications using JS and is easily cross-platform, making it easier to write business logic without worrying about cross-platform issues.
  • Compared to NW, ELECTRON is more widely used, more fully documented and easier to use.
  • The community is powerful, and basically any problem you encounter can be solved in the community.

The official sample

Sample project warehouse $# cloning git clone https://github.com/electron/electron-quick-start # $CD electron - quick to enter the warehouse - start # installation and operation of $ npm install && npm startCopy the code

Project screenshots

Electron installation and packaging tool installation

  • Global installation electron

    npm install electron -g
    Copy the code
  • The local installation

    npm install electron --save-dev
    Copy the code
  • Packaging tools

    The packing tool I’ve chosen here is the electron packager

    Install the packaging tool in the project and configure the command line

    npm install --save-dev electron-packager
    Copy the code

    {
      "name": "qq-music"."version": "1.0.0"."description": "A Vue.js project"."author": "junchang.ma.ele_waimai <[email protected]>"."private": true."scripts": {
        "dev": "Webpack - dev - server - the host 0.0.0.0 - the inline - progress - config build/webpack dev. Conf., js." "."start": "npm run dev"."build": "node build/build.js"."electron_dev": "electron build/electron.js"."electron_build": "electron-packager ./dist/ --platform=darwin --arch=x64 --overwrite"
      },
      "dependencies": {... },"devDependencies": {... },"engines": {
        "node": "> = 6.0.0"."npm": "> = 3.0.0"
      },
      "browserslist": [
        "1%" >."last 2 versions"."not ie <= 8"]}Copy the code

    Command line configuration:

    packager": /app HelloWorld --all --out./OutApp --version 1.4.0 --overwrite --icon=./app/img/icon/icon.ico"Copy the code

    • Location of Project: Indicates the path of the project
    • Name of Project: indicates the name of the packaged project
    • Platform: Determines which platform you want to build the application on (Windows, Mac, or Linux)
    • Architecture: Determines whether to use x86 or X64 or both architectures
    • Electron version: indicates the version of the electron
    • Optional options: Optional options

    The project name, version, icon path in the field should be changed to its own;

Pack electron (integrate electron into VUE)

Refer to the preceding command line configuration

Local Preview mode

  • Generate an electron. Js file in the build folder

    // Modules to control application life and create native browser window
    const {app, BrowserWindow} = require('electron')
    // import path from 'path'
    const path = require('path')
    // Keep a global reference of the window object, if you don't, the window will
    // be closed automatically when the JavaScript object is garbage collected.
    let mainWindow
    
    function createWindow () {
      // Create the browser window.
      mainWindow = new BrowserWindow({width: 800.height: 600})
    
      // and load the index.html of the app.
      mainWindow.loadFile(path.join(__dirname, '.. /dist/index.html'))
    
      // Open the DevTools.
      // mainWindow.webContents.openDevTools()
    
      // Emitted when the window is closed.
      mainWindow.on('closed'.function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null})}// This method will be called when Electron has finished
    // initialization and is ready to create browser windows.
    // Some APIs can only be used after this event occurs.
    app.on('ready', createWindow)
    
    // Quit when all windows are closed.
    app.on('window-all-closed'.function () {
      // On OS X it is common for applications and their menu bar
      // to stay active until the user quits explicitly with Cmd + Q
      if(process.platform ! = ='darwin') {
        app.quit()
      }
    })
    
    app.on('activate'.function () {
      // On OS X it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (mainWindow === null) {
        createWindow()
      }
    })
    
    // In this file you can include the rest of your app's specific main process
    // code. You can also put them in separate files and require them here.
    
    Copy the code

Packaging mode

  1. Copy the lower electron. Js from the build directory into a copy of the dist file

  2. Configure a package.json

    {
      "name": "nw-qqMusic", project name"version": "0.0.1", the version number"main": "electron.js"Project entry file}Copy the code
  3. Run on the command line in the project root directory

    npm run build 
    npm run electron_build
    Copy the code

Nw versus Electron

  1. Nw.js is closer to Node.js in both surface and essence. Nw.js directly inherits and uses the startup, development and running mode of Node.js, with minimal modification to Node.js, while electron changes a lot and adds a lot of its own things, which makes it feel significantly different from Node.js in use. Nw.js is single-process like Node.js, and electron has been changed to double-process.
  2. Advantages of Electron: The open source core extension is relatively easy, the interface is highly customized, in principle, he can do anything the Web can do. Is currently the cheapest cross-platform technology solution, compared to other cross-platform solutions (such as QT GTK+, etc.), more stable, less bug, after all, as long as the browser shell runs, there are not too many problems.
  3. Disadvantages of Electron:
    • Card, slow startup, this is probably webKit’s pot. After all, a browser does have a lot of functionality to support.
    • In addition to the main process you may need to start some helper processes to get the job done. And every time you start a new process, the starting price is a NodeJS memory overhead!
    • Frame loss is the most serious, but I have been used to the silkiness of Native. I feel it can be done in MAC and WIN, which is a bit tough.
    • The bag is too big. (Obviously, even an empty package contains at least the volume of a browser
  4. Nw. js has a deeper library integration, and in a sense, a deeper understanding of Chromium and Node (to use new features, you have to take the source code and build it into it).
  5. According to the license, Electron is Github and nw. js is Intel.
  6. Nw can only build MAC apps on MAC and Windows apps on Windows. Electron can build Linux Macs and Windows from the command line

documents

Qq music interface access to the relevant documents

Blog.csdn.net/xiayiye5/ar… Blog.csdn.net/hhzzcc_/art… Segmentfault.com/a/119000000…

Nw Related information

  • github.com/nwjs/nw.js
  • Blog.csdn.net/tsyccnh/art…

Electron

Build your first electron app

Making the address

Common packaging tools

Electron: Write a notepad app from scratch

Electron packing: electron- Packager and electron- Builder (for Windows)

Summary of common parameters of the electron-packager command

Exploration and Thinking

How many ways can you implement div heights that are also self-adaptive and always in proportion to the width?

Project address and startup mode

Git clone HTTPS//github.com/majunchang/QQ-music.gitInstall NPM I CD nodeServer NPM I start the Node agent in the nodeServer folder NPM run dev local preview (project root directory) NPM run dev local preview NPM run Electron_dev package NPM run build NPM run electron_buildCopy the code