@(工作笔记)

node-record

[TOC]


node版爬虫...

https://github.com/GoogleChrome/puppeteer 踩坑 https://my.oschina.net/javazyw/blog/1585782

如果下载不了 浏览器 就手动下载 在代码中配置...

下载地址: https://download-chromium.appspot.com

参考: https://blog.csdn.net/u010142437/article/details/79126564

  const browser = await puppeteer.launch({
    executablePath:'/Applications/Chromium.app/Contents/MacOS/Chromium',
    args  : ['--no-sandbox'],
    dumpio: false,
  });

获取数组所有排列组合

https://github.com/N-ZOO/everycode/issues/8

var a = [1, 2, 3, 4];

function groupSplit(arr, size) {
    var maxSize = arr.length, groupArr = [];

    if(size >= 1 && size <= maxSize){
        getArr(arr, 0, []);
    }

    function each(arr, index, fn){
        for (var i = index; i < maxSize; i++) {
            fn(arr[i], i, arr);
        }
    }

    function getArr(arr, _size, _arr, index){
        if(_size === size){
            return;
        }

        var len = _size + 1;

        each(arr, index || 0, function(val, i, arr){

            _arr.splice(_size, 1, val);

            if(_size === size - 1){
                groupArr.push(_arr.slice());
            }

            getArr(arr, len, _arr, i + 1);
        });
    }

    return groupArr;
}

var ret = groupSplit(a, 2);
console.log(ret); // [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

静态文件跨域

https://segmentfault.com/q/1010000013603023?sort=created


Alt text

console.log('hello world')

VueLoaderPlugin

官方没写 fuck!!!!!!!!!! 参考: https://gist.github.com/yyx990803/e0f4f1275841f4ce756b8c1ac1db76e9

shelljs

官方API:http://documentup.com/shelljs/shelljs#sedoptions-search_regex-replacement-file_array

sed([options,] search_regex, replacement, file [, file ...])
sed([options,] search_regex, replacement, file_array)
Available options:

-i: Replace contents of file in-place. Note that no backups will be created!
Examples:

sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
Reads an input string from files, and performs a JavaScript replace() on the input
using the given search_regex and replacement string or function. Returns the new string after replacement.

Note:

Like unix sed, ShellJS sed supports capture groups. Capture groups are specified
using the $n syntax:

sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt');

sed使用 js replace实现 , 能跨平台...牛b

global package

babel-cli nrm supervisor webpack webpack-cli webpack-dev-server


shell命令

查看 npm全局路径

## 查看 npm全局路径
npm -g root

安装webpack

cnpm install -g webpack

webpack打包

# 元命令
webpack main.js -o bundle.js --mode development

# 制作成常用脚本
#!/usr/bin/env bash
if [ "$3" == "r" ]; then
  webpack $1 -o $2 --mode production
else
  webpack $1 -o $2 --mode development
fi

webpack配置文件

cnpm init -f
cnpm install babel-loader --save-dev
cnpm install babel-core --save-dev
cnpm install --save-dev babel-preset-react 
cnpm install babel-preset-es2015 --save-dev
cnpm install babel-plugin-transform-object-rest-spread --save-dev

cnpm install --save react react-dom

touch webpack.config.js

printf "  //内置path模块:获取到绝对路径
var path       = require('path');
//暴露一个对象
module.exports = {
  //设置入口文件
  entry : './app/main.js',
  //设置打包文件的文件夹、文件的名字
  output: {
    //设置你的打包的文件的文件夹的名字
    path    : path.resolve(__dirname, 'dist'),
    //设置你的打包的文件的名字
    filename: 'bundle.js'
  },
  //当你的js文件发生变化的时候,你在重新的保存的时候,会自动的再一次的打包
  watch : true,
  //其他模块的设置:翻译器(babel-loader)
  module: {
    //其他模块的规则
    rules: [
      {
        //①翻译的文件的尾缀什么(.js)
        test   : /\.jsx?$/,
        include: [
          path.resolve(__dirname, './app')
        ],
        exclude: [
          path.resolve(__dirname, './node_modules'),
          path.resolve(__dirname, './app/demo-files')
        ],
        //翻译器的设置
        loader : 'babel-loader',
        //其他的选项的设置:设置的预设值、插件
        options: {
          //预设值
          presets: ['es2015', 'react'],
          //插件
          plugins: ['transform-object-rest-spread']
        }
      }
    ]
  }
};" > webpack.config.js

vscode 自定义颜色主题

在线编辑: https://tmtheme-editor.herokuapp.com/#!/editor/local/Sydney

查看官方文档: https://code.visualstudio.com/docs/extensions/themes-snippets-colorizers

您可以使用Command Palette(⇧⌘P)中的Developer:Inspect TM Scopes命令检查光标处的标记范围,并查看已应用哪个标记规则。
检查范围
```
![Alt text](./1523612583265.png)
![Alt text](./1523612538556.png)
![Alt text](./1523612684143.png)

查看Scope元素定位文档:
https://manual.macromates.com/en/scope_selectors

![Alt text](./1523613804111.png)
转
```
source.js meta.function.expression.js meta.block.js meta.function.js meta.block.js meta.var.expr.js variable.other.object.property.js
```

![Alt text](./1523613870243.png)

能起作用...

---

##  node定时任务
https://www.jianshu.com/p/d9797f1afdc8



---

## Node 核心模块之 child_process

<https://www.jianshu.com/p/692d9d2e77a5>



execFile
 语法:child_process.execFile(file[, args][, options][, callback])
 注意:
 1、与 exec 的不同是,命令的参数不能放在第一个参数,只能作为第二个参数传递;
 2、默认情况下不会衍生 shell,指定的可执行 file 直接作为新进程衍生,使其比 child_process.exec() 稍微更高效
 3、file 是要运行的可执行文件的名称或路径,如 node.exe,不能是 start.js 这种脚本文件



##  

## NodeJS中的多进程、集群

<https://juejin.im/post/5bbd83f5e51d450e894e4f3a>



---

```plain
<--- Last few GCs --->

[81312:0x10286a000]   787091 ms: Mark-sweep 1393.6 (1425.2) -> 1393.2 (1425.7) MB, 1294.4 / 0.0 ms  (average mu = 0.234, current mu = 0.048) allocation failure scavenge might not succeed
[81312:0x10286a000]   789143 ms: Mark-sweep 1393.8 (1425.7) -> 1393.5 (1425.2) MB, 2035.9 / 0.0 ms  (average mu = 0.121, current mu = 0.008) allocation failure scavenge might not succeed


<--- JS stacktrace --->

==== JS stack trace =========================================
```

<https://stackoverflow.com/questions/53230823/fatal-error-ineffective-mark-compacts-near-heap-limit-allocation-failed-javas>



就我而言,请安装NodeJs 12.10.0版来解决此问题



尝试在论坛上的旧消息中指出的解决方案:[https](https://forum.ionicframework.com/t/3-7-0-ios-build-with-prod-not-working/107061/24) : [//forum.ionicframework.com/t/3-7-0-ios-build-with-prod-not-working/107061/24](https://forum.ionicframework.com/t/3-7-0-ios-build-with-prod-not-working/107061/24)

打开 `node_modules/@ionic/app-scripts/bin/ionic-app-scripts.js`

将第一行从:

```js
#!/usr/bin/env node
```

至

```js
#!/usr/bin/env node --max-old-space-size=4096
```

尝试使用值1024和2048,但是对于相对较大的应用,您可能需要4096。





```sh
export NODE_OPTIONS="--max-old-space-size=5120" #increase to 5gb
export NODE_OPTIONS="--max-old-space-size=6144" #increase to 6gb
export NODE_OPTIONS="--max-old-space-size=7168" #increase to 7gb
export NODE_OPTIONS="--max-old-space-size=8192" #increase to 8gb

# and so on...

# formula:
export NODE_OPTIONS="--max-old-space-size=(X * 1024)" #increase to Xgb

# Note: it doesn't have to be multiples of 1024. 
# max-old-space-size can be any number of memory megabytes(MB) you have available.
```





```js
node --max-old-space-size=X node_modules/@angular/cli/bin/ng build --prod
```

---

gzip頁面

```javascript
const request  = require('request')
const zlib     = require('zlib')

function reqHtml(url) {
  return new Promise((resolve, reject) => {
    let options = {
      'url'   : url,
      'method': 'GET',
      encoding: null,
      headers : {
        'User-Agent'     : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
        // 'Referer'   : `http://video.eyny.com/video`,
        'Accept'         : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Accept-Encoding': 'gzip',
      },
      proxy   : 'http://127.0.0.1:1087',
    }
    // console.log(options)
    request(options, async function (error, response, body) {
      if (!error && response.statusCode === 200) {
        // resolve(JSON.parse(body))
        zlib.unzip(body, function (err, buffer) {
          console.log(buffer.toString())
          resolve(buffer.toString())
        })
      } else {
        reject({ url, error, statusCode: response.statusCode })
      }
    })
  })
}
```

--unsafe-perm

npm --registry=https://registry.npm.taobao.org i --unsafe-perm

出现上面的问题可执行下面这条指令:

npm方面 引用自:https://segmentfault.com/q/1010000019365121/

npm 出于安全考虑不支持以 root 用户运行,即使你用 root 用户身份运行了,npm 会自动转成一个叫 nobody 的用户来运行,而这个用户几乎没有任何权限。这样的话如果你脚本里有一些需要权限的操作,比如写文件(尤其是写 /root/.node-gyp),就会崩掉了。

为了避免这种情况,要么按照 npm 的规矩来,专门建一个用于运行 npm 的高权限用户;要么加 --unsafe-perm 参数,这样就不会切换到 nobody 上,运行时是哪个用户就是哪个用户,即使是 root。


linux安装中文字体

https://www.cnblogs.com/huangyanqi/p/10609587.html


Node.js中的require.resolve方法使用简介

在Node.js中,可以使用require.resolve函数来查询某个模块文件的带有完整绝对路径的文件名,下面这篇文章主要介绍了Node.js中require.resolve方法使用的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

网上关于NodeJs的论述很多,此处不多说。个人认为,NodeJs的编程思想和客户端Javascript保持了一种理念,没有什么变化,只是增加了“require()”函数,因此只要学好require函数,剩下的问题就是如何更好的使用API了。本文则主要介绍了Node.js中的require.resolve方法,下面来看看详细介绍吧。

简单的说,在 Node.js 中使用 fs 读取文件的时候,经常碰到要拼一个文件的绝对路径的问题 (fs 处理相对路径均以进程执行目录为准)。

之前一直的方法都是,使用 path 模块以及 __dirname 变量 。

代码如下所示:

fs.readFileSync(path.join(__dirname, ``'./assets/some-file.txt'``));

使用 require.resolve 可以简化这一过程

示例代码:

fs.readFileSync(require.resolve(``'./assets/some-file.txt'``));

此外, require.resolve 还会在拼接好路径之后检查该路径是否存在, 如果 resolve 的目标路径不存在, 就会抛出 Cannot find module './some-file.txt'的异常. 省略了一道检查文件是否存在的工序 (fs.exists).

这个报错并不会加重你的检查负担, 毕竟使用 fs 去操作文件时, 如果发现文件不存在也会抛出异常. 反之, 通过 require.resovle 可以在提前在文件中作为常量定义, 那么在应用启动时就可以抛异常, 而不是等到具体操作文件的时候才抛异常.

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。谢谢大家对脚本之家的支持。

本地包强制重新安装

本地包强制重新安装

npm install ../xxx -f (只是单纯安装(install)或更新(update)没用,因为version没变)

How can I use an ES6 import in Node.js? [duplicate]

https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node-js

Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling.

TLDR;

Node.js >= v13

It's very simple in Node.js 13 and above. You need to either:

  • Save the file with .mjs extension, or
  • Add { "type": "module" } in the nearest package.json.

You only need to do one of the above to be able to use ECMAScript modules.

Node.js <= v12

If you are using Node.js version 9.6 - 12, save the file with ES6 modules with .mjs extension and run it like:

node --experimental-modules my-app.mjs

node 的path模块中 path.resolve()和path.join()的区别

https://blog.csdn.net/qq_33745501/article/details/80270708

三、path.resolve([from...],to)

作用:把一个路径或路径片段的序列解析为一个绝对路径。相当于执行cd操作。

/被解析为根目录。


axios proxy

https://www.npmjs.com/search?q=%20https-proxy-agent

Axios proxy is not working. #2072

https://github.com/axios/axios/issues/2072


Copy to clipboard in Node.js?


绑定软连接

进入项目之后 执行命令 npm link

前提是 bin 字段和 main 字段 设置好

{
  "name": "stone-cli",
  "version": "1.0.0",
  "description": "stone-cli",
  "main": "index.js",
  "bin": {
    "stone": "index.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/stone0117/stone-cli.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/stone0117/stone-cli/issues"
  },
  "homepage": "https://github.com/stone0117/stone-cli#readme",
  "dependencies": {
    "commander": "^9.0.0",
    "download": "^8.0.0",
    "download-git-repo": "^3.0.2",
    "ejs": "^3.1.6",
    "lodash": "^4.17.21",
    "open": "^8.4.0"
  },
  "devDependencies": {
    "@types/ejs": "^3.1.0"
  }
}

results matching ""

    No results matching ""