次のようなコレクション系データがあったとします。
var = stageItems: [
{ id: 5, name: "山田" },
{ id: 6, name: "斎藤" },
{ id: 7, name: "朝倉" },
{ id: 8, name: "神山" },
];
// id = 6 なアイテムを選択します
const item = _.find(this.stageItems, { id:6 });
// id = 6 が 何番目の要素なのかを検索 ( 0 が先頭 )
const added_i = this.stageItems.findIndex(({id}) => id === 6);
alert( added_i ); // 2番目の要素なので 1
itemDelete: function ( argId ) {
alert("このidを削除します" + argId);
this.stageItems = _.remove(this.stageItems, function (o) { return o.id !== argId; });
},
JavaScriptではオブジェクトのコピーは参照コピーとなります。 オブジェクトをディープコピーしたい場合はこちらのメソッドを使用します
const clonedItem = _.cloneDeep(item);
https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore
// Underscore/Lodash
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = _.pluck(array1, "name")
console.log(names)
// output: ["Alice", "Bob", "Jeremy"]
// Native
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = array1.map(function(x){
return x.name
})
console.log(names)
// output: ["Alice", "Bob", "Jeremy"]
// Underscore/Lodash
var array = [1, 2, 1, 4, 1, 3]
var result = _.uniq(array)
console.log(result)
// output: [1, 2, 4, 3]
// Native
var array = [1, 2, 1, 4, 1, 3];
var result = [...new Set(array)];
console.log(result)
// output: [1, 2, 4, 3]
// Underscore/Lodash
console.log(_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]))
// output: [1, 2]
// Native
var arrays = [[1, 2, 3], [101, 2, 1, 10], [2, 1]];
console.log(arrays.reduce(function(a, b) {
return a.filter(function(value) {
return b.includes(value);
});
}));
// output: [1, 2]
// ES6
let arrays = [[1, 2, 3], [101, 2, 1, 10], [2, 1]];
console.log(arrays.reduce((a, b) => a.filter(c => b.includes(c))));
// output: [1, 2]
// Lodash
var object = { a: 1, b: 'settings', c: { d: 'test' } };
var hasA = _.has(object, 'a');
var hasCWhichHasD = _.has(object, 'c.d')
console.log(hasA);
// output: true
console.log(hasCWhichHasD);
// output: true
// Native
const has = function (obj, key) {
var keyParts = key.split('.');
return !!obj && (
keyParts.length > 1
? has(obj[key.split('.')[0]], keyParts.slice(1).join('.'))
: hasOwnProperty.call(obj, key)
);
};
var object = { a: 1, b: 'settings' };
var result = has(object, 'a');
// output: true
npm install pm2@latest -g
vi app.json
app.json を次の内容で保存する
{
"name" : "nextjs",
"script" : "./node_modules/next/dist/bin/next",
"env" : {
"NODE_ENV" : "development"
},
"env_production" : {
"NODE_ENV" : "production"
}
}
"name" : "nextjs", としているので、アプリ名は nextjs になります。
pm2 start app.json --env production
起動すると nextjs というアプリがリストに表示されます。
プロセスの状態を見る
pm2 ls
「nextjs」という名前のアプリを停止する
pm2 stop nextjs
「nextjs」という名前のアプリをプロセスリストからする
pm2 delete nextjs
「nextjs」という名前のアプリをリスタートする
pm2 restart app_name
pm2 を自動起動させる( centos )
pm2 startup
pm2 を自動起動させる
pm2 save
npx create-next-app
実行するとサイト名を
What is your project named? …
と聞かれますので入力します。( 例: test-app)
アプリ名を指定して新規作成する場合は
npx create-next-app --example parameterized-routing test-app
のようにすると
example指定: parameterized-routing
アプリ名: test-app
で新規作成します。
npm run dev
npm run build
npm run start
新規ファイルを作成
vi pages/page01.js
import Head from 'next/head'
import styles from '../styles/Home.module.css'
export default function Home() {
return (
<div>
<h1>Hello page01</h1>
</div>
)
}
これが URL
http://localhost:3000/page01
にあたります。
<Link href="/page02">
<button>page02</button>
</Link>
package.json
{
"scripts": {
...
"build_static": "next build && next export -o dist",
},
( "build_static"の行を追加します )
ビルドの実行
npm run build_static
/dist/ フォルダに書出が行われます。
JSON ファイルにコメントを記述することはできませんが以下のように無効なパラメーターとして登録しておくことでコメントを対応させることができます。
_comment にコメントを記述する
{
"_comment": "comment text goes here...",
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
}
}
}
}
npm i puppeteer
vi example.js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await browser.close();
})();
node example.js
npm install -g vsce
npm install -g yo
yo doctor
vsce --version
1.81.1
バージョン番号が返ってくればOKです。
Azure Dev Ops にログインして「Profile」→「Personal access tokens」から Personal Access Tokens を作成します。
設定はこちらを参考にします。
作成したトークンをコピーしておきます。
vsce login akat03
(コピーしておいたトークンを使ってログインします)
作成した拡張をgithubにpushします。(詳細は割愛します)
"icon": "icon.png",
"repository": {
"type": "git",
"url": "https://github.com/xxxxx/YOUR-GIT-PROJECT-NAME"
},
"bugs": {
"url": "https://github.com/xxxxx/YOUR-GIT-PROJECT-NAME/issues"
},
vsce publish -p <token>
npm ls で deduped がたくさん出るようなら yarn への乗り換えを検討しましょう。
● yarn を使用する
brew install yarn
● yarn のバージョンを確認する
yarn -v
1.19.1
● npmの代わりに yarn を使用する
npm install image-js
↓
yarn add image-js
Webpack4 + Babel を使用して IE11 での動作を確認する。
ローカルにインストールします( サイズはさほど大きくなく、46MB 程度なので複数のローカル環境に入れてもあまりディスクの負担になりません)
webpackとwebpack-cliとwebpack-dev-serverをインストールする
cd YOUR-PROJECT-FOLDER
npm install webpack webpack-cli webpack-dev-server -D
npm init -y
なお、オプションの -D は --save-dev と同じです
https://docs.npmjs.com/misc/config
./src/index.js
import {hellowebpack} from './f';
hellowebpack();
./src/f.js
export function hellowebpack() {
alert('hellowebpack!!!');
}
npx webpack
./dist/main.js が以下のような内容で作成されます
!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";r.r(t),alert("helloメソッドが実行された。")}]);
javascriptのコードが圧縮されています。
これは 「 mode: 'production' 」な本番仕様です。
開発環境では圧縮しない 「 mode: 'development' 」を使用することでコンパイル時間を圧倒的に短縮することができます。
( ↓ やり方はこの後で)
webpack.config.js
watch: true を追加すると watch します
module.exports = {
........................
watch: true
};
./dist/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>webpack test</title>
<script src="./main.js"></script>
</head>
<body>
</body>
</html>
mode: 'development' の記述はここに行います。
module.exports = {
devtool: 'inline-source-map' ,
mode: 'development', // (development: 開発 production: 本番)
entry: './src/index.js',
output: {
path: `${__dirname}/dist`,
filename: 'main.js'
},
devServer: {
contentBase: 'dist',
open: true
}
};
npx webpack-dev-server
これでサーバが起動し、自動的に ./dist/index.html を読み込んで「hellowebpack!!!」アラートが表示されれば成功です。
webpack-dev-serverを起動しておくと、対象ファイルが更新された時に自動でリコンパイルがかかります。 それを確認してみます。
./src/f.js を以下のように変更して保存する
export function hellowebpack() {
alert('hellowebpack!!! 変更しました。');
}
ブラウザに切り替えて、自動的に更新されていることを確認します。
自動更新機能は便利ですね!
「control + c 」で webpack-dev-serverを終了してから webpack ビルドを行う。
npx webpack
./dist/ 以下の全てのファイルを本番WEBサーバへアップロードして表示させて確認します。
webpack ではデフォルトでは js しか読み込めません。 css を読み込むようにするには
style-loader css-loader をインストールする
npm i -D style-loader css-loader
webpack.config.js の設定項目の一番下に以下を追加します。
module: {
rules: [
{
test: /\.css/,
use: [
'style-loader',
{loader: 'css-loader', options: {url: false}},
],
},
]
}
● webpack で js 以外に scss (sass) も読み込めるようにする こちらが今一番WEB制作的には一番現実的でしょう。
npm i -D webpack webpack-cli sass-loader sass style-loader css-loader
webpack.config.js を次のようにします。
// [定数] webpack の出力オプションを指定します
// 'production' か 'development' を指定
const MODE = "development";
// ソースマップの利用有無(productionのときはソースマップを利用しない)
const SOURCEMAP_FLAG = MODE === "development"; // true or false
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
// モード値を production に設定すると最適化された状態で、
// development に設定するとソースマップ有効でJSファイルが出力される
mode: MODE ,
module: {
rules: [
{
// 対象となるファイルの拡張子(scss)
test: /\.scss$/,
// Sassファイルの読み込みとコンパイル
use: ExtractTextPlugin.extract([
// CSSをバンドルするための機能
{
loader: 'css-loader',
options: {
// オプションでCSS内のurl()メソッドの取り込まない
url: false,
// ソースマップの利用有無
sourceMap: true,
// Sass+PostCSSの場合は2を指定
importLoaders: 2
},
},
// PostCSSのための設定
{
loader: 'postcss-loader',
options: {
// PostCSS側でもソースマップを有効にする
sourceMap: true,
// ベンダープレフィックスを自動付与する
plugins: () => [require('autoprefixer')]
},
},
// Sassをバンドルするための機能
{
loader: 'sass-loader',
options: {
// ソースマップの利用有無
sourceMap: SOURCEMAP_FLAG,
}
}
]),
},
],
},
plugins: [
new ExtractTextPlugin('style.css'),
],
// source-map方式でないと、CSSの元ソースが追跡できないため
devtool: "source-map"
};
引用元 : https://qiita.com/hiroseabook/items/383d54a87fd5ab4108bc
ES6で書いたJavaScriptは IE11 では使えないので babel をwebpackから呼び出してIE11でも使える状態でコンパイルします
./src/Myclass.js
export class Myclass {
constructor(id,userName) {
this.id = id;
this.userName = userName;
}
alertUserName() {
alert(this.userName);
}
}
./src/Myclass.js
import {hellowebpack} from './f';
import {Myclass} from './Myclass.js';
hellowebpack();
var m = new Myclass(1, 'DOWN TOWN');
m.alertUserName();
npm install -D webpack webpack-cli babel-loader @babel/core @babel/preset-env
webpackと合わせると 70MB くらいになります
下記のように書き換えます。
module.exports = {
mode: 'production', // development or production
entry: './src/index.js',
output: {
path: `${__dirname}/dist`,
filename: 'main.js'
},
devServer: {
contentBase: 'dist',
open: true
} ,
module: {
rules: [{
test: /\.js$/,
use: [{
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
]
}
}]
}]
}
};
npx webpack
本番サーバへアップロードして IE11で確認します。
Express を立ち上げるほどではないときは次のようにしてサーバを立ち上げます。
myserver.js
var fs = require('fs');
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
fs.readFile(__dirname + '/index.html', 'utf-8', function (err, data) {
if (err) {
res.writeHead(404, {'Content-Type' : 'text/plain'});
res.write('page not found');
return res.end();
}
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(data);
res.end();
});
});
server.listen(1337, '127.0.0.1');
console.log( 'Server Started.\nopen "http://127.0.0.1:1337/"' );
実行方法
node myserver.js
でWEBサーバを立ち上げた後 http://127.0.0.1:1337/ へアクセスします。
ターミナルから以下を実行します。
brew install anyenv
echo 'eval "$(anyenv init -)"' >> ~/.bash_profile
echo $SHELL -l
一旦ターミナルを終了して、再度起動。
メッセージが出るので次のコマンドを実行
anyenv install --init
anyenv install nodenv
exec $SHELL -l
これでインストールは完了です。
nodenv install -l
nodenv install 9.11.2
nodenv global 9.11.2
フォルダ「my-project」以下は v6.3.0 を使用するようにセットします
cd my-project
nodenv install 6.3.0
nodenv local 6.3.0
これで、フォルダ「my-project」以下は必ず 6.3.0 になります。
node -v
正しくバージョンが表示されればOKです。
nodenv versions
touch $(nodenv root)/default-packages
cd ${NODENV_ROOT}
git pull
cd ${NODENV_ROOT}/plugins/node-build/
git pull
https://packagecontrol.io/packages/JsPrettier
Sublime Textのパッケージコントローラーからインストールします
(command + shift + p) →【Install Package を選択】→【Js Prettierを選択】
【Package settings】→【JsPrettier】→【settings - Default】を選択して設定ファイルを開きます
次の2つの項目のパスを設定します。
例:)
"prettier_cli_path": "/Users/hogehoge/.nodebrew/current/bin/prettier",
"node_path": "/Users/hogehoge/.nodebrew/current/bin/node",
which prettier
which node
(command + shift + p) →【JsPrettier:Format Codeを選択】
とても便利なのでぜひショートカットを設定しましょう。
// JsPrettier
{ "keys": ["ctrl+p"], "command": "js_prettier" } ,
今時ES6 JavaScriptで記述することが多くなったので
コード検証ツールにESLint、自動整形ツールにPrettierをインストールしてSublimeTextから使用できるようにします。
npm install -g eslint
npm install -g prettier
ここまでの状態で自動整形のテストを行います
test.js ファイルを用意して自動整形してみます
prettier test.js
ターミナル画面(標準出力)に自動整形した結果が表示されます。
実際に自動整形してファイルを更新するには( --write )オプションを使用します。
prettier --write test.js
eslint test.js と行きたいところですが、まず設定ファイルを作成します。 懸賞したいファイルがあるディレクトリから
eslint --init
を実行すると対応形式で設定ファイル( .eslintrc.js )が生成されます こんなファイルです
module.exports = {
"env": {
"browser": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
eslint test.js
でソースコードの検証が実行されます。
.eslintrc editor
https://pirosikick.github.io/eslintrc-editor/
「Airbnb JavaScript Style Guide」はなかなか厳格なルールなので
既存のプロジェクトにいきなり当てはめるには無理がありますが
どの程度厳格なソースフォーマット指定なのか体験しておくだけでも価値があると思います
https://github.com/airbnb/javascript
npm init -y
npm install --save-dev eslint-config-airbnb eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y eslint
{
"extends": "airbnb"
}
node.jsでオブジェクトの中身を一気に表示するにはconsole.logで表示しても良いのですが
次のようにすると楽に見れます
npm install util --save-dev
通常
console.log(results);
とする代わりに
var util = require('util');
console.log(util.inspect(results,false,null));
とします。
システムの開発がphpかつテンプレートエンジンTwigを使用する場合
デザイン過程で静的なhtmlを作成する場合にもTwigを使用しておくとプログラムへのテンプレート化する時に
作業を省くことができます
実はGulpにはPHPと同じTwigテンプレートがあるのでこちらを使用します。
node.js とgulp はあらかじめインストールしておきます。
npm install gulp-twig --save-dev
以下の仕様でコンパイルするよう設定を記述します
● ./twig/ ディレクトリ以下の全ての html ファイルをTwigテンプレートを使用してコンパイルし、./www/ ディレクトリ内に生成する。
● アンダースコアで始まるファイルはコンパイルしない。
gulpfile.js 以下のとおり作成する
// twig コンパイル設定
var gulp = require('gulp');
var twig = require('gulp-twig');
var rename = require('gulp-rename');
gulp.task('twig', function () {
'use strict';
gulp.src(['./twig/*.html', './twig/*/*.html', '!./twig/_*.html'])
.pipe( twig({}) )
.pipe(gulp.dest('./www/'));
});
gulp twig
テンプレートファイル内に以下のように記述します
{{ _target.relative }}
{{ _self.getTemplateName().__toString }}
_layout.htm
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<header></header>
<div class="container">
{% block content %}{% endblock %}
</div>
<footer></footer>
</body>
</html>
<!-- {{ template_filename }} -->
index.htm
{# 継承元 #}
{% extends "_layout.htm" %}
{# ファイル名 #}
{% if _self.getTemplateName() %}
{% set template_filename = _self.getTemplateName().__toString %}
{% else %}
{% set template_filename = _target.relative %}
{% endif %}
{# ページタイトル #}
{% set title = 'ユーザー管理・データ編集の完了' %}
{% block title %}{{ title }}{% endblock %}
{# コンテンツ #}
{% block content %}
<!-- ここにコンテンツを記述します -->
...
...
...
<!-- ここにコンテンツを記述します -->
{% endblock %}
上の2つのファイルを用意して test.htm を gulp-twig でコンパイルすると次のようなファイルが生成されます。
test.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ユーザー管理・データ編集の完了</title>
</head>
<body>
<header></header>
<div class="container">
<!-- ここにコンテンツを記述します -->
...
...
...
<!-- ここにコンテンツを記述します -->
</div>
<footer></footer>
</body>
</html>
<!-- test.html -->
electonとは html や css や javascript などといった web 制作の技術を使ってデスクトップ上のアプリケーションを制作しようというものです。 ( まず node js が必要になりますので node js のインストールを完了させておいてください )
npm install -g electron
npm install -g electron-packager
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Electron!</title>
</head>
<body>
<h1>Hello Electron!</h1>
Node version: <script>document.write(process.versions.node)</script>,
Chrome version: <script>document.write(process.versions.chrome)</script>,
Electron version: <script>document.write(process.versions.electron)</script>.
</body>
</html>
main.js
const { app, BrowserWindow } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL(`file://${__dirname}/index.html`);
win.on('closed', () => {
win = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (win === null) {
createWindow();
}
});
package.json
{
"name": "myapp",
"version": "0.0.1",
"main": "main.js"
}
electron .
electron -v
(例 : v1.6.2)
electron-packager <ディレクトリ> <アプリ名(拡張子は除く)> --platform=darwin,win32 --arch=x64 --version=<バージョン> --overwrite
https://qiita.com/tags/electron
https://teratail.com/questions/search?q=electron&search_type=and
http://bit.ly/2nYCc4d
http://bit.ly/2n8dA47
https://github.com/djyde/iCultus
https://github.com/theodi/comma-chameleon
http://sachinchoolur.github.io/lightgallery-desktop/
nodebrew を使って以下のパッケージをインストールします
brew cask install xquartz(途中で管理者パスワードの入力を求められます)
brew install wine
brew uninstall nodebrew
brew uninstall node
curl -L git.io/nodebrew | perl - setup
.bashrc の最後にパスを追加
cd
vi .bash_profile
下記の2行を追加します
# nodebrew
export PATH=$HOME/.nodebrew/current/bin:$PATH
正しくインストールされたか確認します。
source ~/.bash_profile
nodebrew help
バージョンが表示されればOKです。
nodebrew ls-remote
nodebrew install-binary v9.5.0
nodebrew list
nodebrew use v9.5.0
node -v
バージョン名が正しく表示されればOKです。
npm install sqlite3
sqlite3 mydb.sqlite3
CREATE TABLE user_dt (
data_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name TEXT,
modified_date DATETIME
);
.quit
```
var sqlite3 = require('sqlite3').verbose();
var mydb = new sqlite3.Database('./mydb.sqlite3');
mydb.run("INSERT INTO user_dt (user_name,modified_date) VALUES ('taro yamada', datetime('now', 'localtime') )");
```
##● スクリプトを実行してデータベースにデータを1件登録する
```
node test.js
```
##● node.js + sqlite3 で使用できる クエリービルダー
http://knexjs.org
https://hiddentao.com/squel/
##● node.js + sqlite3 で使用できる O/Rマッパー
http://docs.sequelizejs.com/en/v3/
ヘッドレスブラウザとは「画面がないWEBブラウザ」の事です。
最近では Headless Chrome が人気です。 参考 : https://goo.gl/NQsFS2
が、npm だけでインストールできる phantomJS を紹介します。
WebKit(Safari) ベースのヘッドレス(画面なし)ブラウザ
npm install phantomjs
以下のパスを手動で追加します
./node_modules/phantomjs/bin/phantomjs
brew install phantomjs
yum -y install freetype
yum -y install fontconfig
npm install -g phantomjs
Gecko(firefox) ベースのヘッドレス(画面なし)ブラウザ
brew install slimerjs
npm install -g slimerjs
ヘッドレスブラウザを簡単に扱うライブラリ(JavaScript)です。 このcasperJSから「phantomJS」または「slimerJS」を操作します。
brew install casperjs
yum -y install freetype
yum -y install fontconfig
npm install -g casperjs
test.js で下記コードを保存
var AnchorArrays = [];
var casper = require('casper').create();
casper.start('http://flatsystems.net/kakunin.php', function() {
});
casper.then(function() {
casper.wait(3000, function() {
// xpath要素の取得
var xpath = "//*[@id='my_id']";
var element = this.evaluate(function(path){
return __utils__.getElementByXPath(path).innerHTML;
},xpath);
console.log( element );
//png
this.capture('kakunin.png');
console.log( 'キャプチャを作成しました。' );
});
});
casper.run();
casperjs test.js
casperjs --engine=slimerjs test.js
slimerJSで起動するときは --engine=slimerjs を追加します。
https://chrome.google.com/webstore/detail/resurrectio/kicncbplfjgjlliddogifpohdhkbjogm
Mac OSX の場合は brew でインストールできます
brew install slimerjs
インストールが完了したらバージョンを確認しておきます
slimerjs -v
```
var page = require("webpage").create();
page.open('http://zozo.jp/')
.then(function(status){
if(status === 'success'){
console.log(page.title);
page.render('test.png');
}
phantom.exit();
});
```
実行します
```
slimerjs test.js
```
# slimerjs をCUI環境で実行させる
slimerjsはGUI環境下でないと動作しません。
CUIで実行すると
```
slimerjs --debug=true XXXXX.js
```
```
Error: no display specified
```
というエラーになります。
そこで CUI でも実行できるように Xvfb( X virtual framebuffer ) をインストールします。
```
yum -y install xorg-x11-server-Xvfb
```
Xvfbの使い方は 実行したい処理の前に ```xvfb-run``` を付け加えます
```
Xvfb slimerjs --debug=true XXXXX.js
```
これでCUI下の環境でも実行できます。
Heroku上でヘッドレスWEBブラウザ phantom.js を使用するにはビルドパックを追加します。 ビルドパックをGithub上で公開してくれている方がいるのでありがたく利用させていただきます。
https://github.com/stomita/heroku-buildpack-phantomjs
ターミナルから以下を実行
cd "アプリのあるディレクトリ"
heroku login
heroku buildpacks:add --index 1 https://github.com/stomita/heroku-buildpack-phantomjs
git push heroku master
heroku run phantomjs -v
バージョンが帰ってくればOK
`
phantom_test.js`
ファイルを以下の内容で作成します。var page = require('webpage').create();
page.open('http://yahoo.co.jp/', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});
git add .
git commit -m "add buildpack"
git push heroku master
heroku run phantomjs phantom_test.js
「Status: success」が帰ってくればOK
フォントは `
./fonts`
ディレクトリに .ttf フォントファイルを置いて git push すればOKです。
フォントファイルは著作権に注意して使用しましょう
https://www.google.com/get/noto/#sans-jpan
heroku run fc-match sans:lang=ja
Buildpacks | Heroku Dev Center
heroku buildpacks
heroku buildpacks:set "ビルドパック名またはURL"
heroku buildpacks:add "ビルドパック名またはURL"
heroku buildpacks:remove "ビルドパック名またはURL"
heroku buildpacks:clear
node.js から phantomJSを使用するには下記2つの方法がおすすめです。
npm install nightmare
npm install vo
`
test.js`
で保存var Nightmare = require('nightmare');
var google = new Nightmare()
.viewport(1000, 1000)
.useragent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36")
.goto('http://google.com')
.evaluate(function () {
return {
title: document.title,
href : location.href
};
})
.run(function(err, nightmare) {
if (err) return console.log(err);
console.log('Done!');
console.log(nightmare);
});
node test.js
GoogleホームページのタイトルとURLが表示されればOKです。
`
niconico_login.js`
で保存var Nightmare = require('nightmare');
var vo = require('vo');
vo(function* () {
var nico_id = '###メールアドレス###';
var nico_pass = '###パスワード###';
var nightmare = Nightmare({ show: true });
var link = yield nightmare
.goto('https://account.nicovideo.jp/login')
.type('input[id="input__mailtel"]', nico_id)
.type('input[id="input__password"]', nico_pass)
.click('#login__submit')
.wait(2000)
.then(function() {
console.log('終了しました');
});
yield nightmare.end();
return link;
})(function (err, result) {
if (err) return console.log(err);
});
node niconico_login.js
ニコニコ動画にログインできればOKです。
npm install node-horseman
`
test.js`
で保存var Horseman = require('node-horseman');
var horseman = new Horseman();
var filename = 'test.png';
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.open('http://www.google.com')
.type('input[name="q"]', 'github')
.click('[name="btnK"]')
.keyboardEvent('keypress', 16777221)
.waitForSelector('div.g')
.count('div.g')
.log() // prints out the number of results
.screenshot(filename)
.log(filename)
.close();
node test.js
Googleの検索結果の画面が test.png に保存されれば正常に動作しています。
brew install phantomjs
http://phantomjs.org/download.html
console.log('Hello, world!');
phantom.exit();
phantomjs hello.js
Hello, world!が表示されればインストール成功です。
var page = require('webpage').create();
page.open('http://www.yahoo.co.jp', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('page.png');
}
phantom.exit();
});
phantomjs page.js
同じフォルダに page.png というキャプチャ画像があれば成功です。
(「ユーザー登録してWEBアプリをデプロイしてHeroku上で実行する」までの方法)
https://www.heroku.com/
からユーザー登録を行う
https://devcenter.heroku.com/articles/heroku-command-line
からインストーラをインストール
heroku login
git clone https://github.com/heroku/ruby-getting-started.git
cd ruby-getting-started
heroku create
ここまで行うとURLが自動発行されます
https://XXXXX.herokuapp.com/ | https://git.heroku.com/XXXXX.git
git pushします
git push heroku master
No such app as XXXXX. というエラーが出るときは
git remote rm heroku
としてから
heroku create
git push heroku master
とします。
ブラウザで開く
heroku open
cd "アプリのディレクトリ"
git init
git add .
git commit -m "first commit"
heroku create
git push heroku master
heroku open
git add .
git commit -m "change xxxxx"
git push heroku master
heroku open
heroku login
「メールアドレス」「パスワード」を入力してログインします。
heroku apps
と入力すると herokuアプリが
hogehoge-fugafuga-12345
hunihuni-furifuri-67890
という風に表示されます。
アプリ hogehoge-fugafuga-12345 をブラウザで表示するには
heroku open --app hogehoge-fugafuga-12345
と入力します。 またはブラウザのアドレス欄に直接
https://hogehoge-fugafuga-12345.herokuapp.com
と入力してもOKです。
アプリ hogehoge-fugafuga-12345 を削除するには
heroku apps:destroy --app hogehoge-fugafuga-12345 --confirm hogehoge-fugafuga-12345
heroku apps:destroy --app hogehoge-fugafuga-12345
heroku run bash
・Heroku上のホームディレクトリのファイル一覧を表示
heroku run pwd ; ls -la
・Heroku上のphantomjsのバージョンを表示
heroku run phantomjs -v
node.js - How can I run latest version of node on Openshift? - Stack Overflow
Google App Engine Node.jsを試してみる。 GAE/Node.js - Qiita
Google App Engineを無料で運用する方法(2016年版) - koni blog
>Node.jsでWEBページのスクレイピングを行う際に必要となる文字コードの変換と、cheerioによってパースしたHTMLをjQueryのように操作できるHTTPクライアントモジュールです。
特徴 : 文字コード自動変換 , jqueryライクなセレクタ , フォーム簡易送信機能
https://www.npmjs.com/package/cheerio-httpcli
npm install cheerio-httpcli
>HTML/XML parser and web scraper for NodeJS.
特徴 : xpathで要素の取得が可能 , Aタグのリンクを自動的に辿れる
https://www.npmjs.com/package/osmosis
マニュアル : https://github.com/rchipka/node-osmosis/wiki
npm install osmosis
【osmosis node.js】で検索した結果のリンクURLをスクレイピングします。
var osmosis = require('osmosis');
var url = 'https://www.google.co.jp/search?client=safari&rls=en&q=osmosis&ie=UTF-8&oe=UTF-8&gfe_rd=cr&ei=JXMyWLv2NOjC8AernaPYAg#q=osmosis+node.js';
osmosis
.get(url)
.paginate("//*[@id='pnnext']",3) // 最大 3ページ目まで
.set({
'link_url' : ["//*[@id='rso']//h3/a/@href"] ,
'link_title': ["//*[@id='rso']//h3/a"] ,
})
.then(function( context, data){
// console.log(context.request);
console.log(data);
})
.done(function(){
console.log("=================================\nscrape done.\n");
});
その他のスクレイピングモジュール : http://blog.webkid.io/nodejs-scraping-libraries/