2017-04-24 86 views
0

我是新來的節點,我想在命令行中使用節點循環槽命令。命令是這樣的:通過命令行窗口在節點中循環

node dist/main.js dist/index.html dynamic/
node dist/main.js dist/index.html dynamic page.html 
node dist/main.js dist/index.html dynamic page2.html 

我使用angular4普遍和重新呈現我的網頁我必須把這些命令在命令提示符。如果我已經沒有20頁,而且還會更多,這不會成爲問題。我的手變酸了嘿嘿..

我該怎麼做?

謝謝!

的main.js文件

import 'zone.js/dist/zone-node'; 
import { renderModuleFactory } from '@angular/platform-server' 
import { enableProdMode } from '@angular/core' 
import { AppServerModuleNgFactory } from './src/app.server.module.ngfactory' 
import * as fs from 'fs'; 
import * as path from 'path'; 
enableProdMode(); 
const args = process.argv.slice(2); 
if (args.length != 3) { 
    process.stdout.write("Usage: node dist/main.js <document> <distDir> <url>\n"); 
    process.exit(); 
} 
const indexFileContent = fs.readFileSync(args[0], 'utf8'); 
renderModuleFactory(AppServerModuleNgFactory, { 
    document: indexFileContent, 
    url: args[2] 
}).then(string => { 
    let destUrl = args[2]; 
    if (destUrl == '/') 
     destUrl = 'index.html' 
    const targetDir = args[1] + '/' + destUrl; 
    targetDir.split('/').forEach((dir, index, splits) => { 
     if (index !== splits.length - 1) { 
      const parent = splits.slice(0, index).join('/'); 
      const dirPath = path.resolve(parent, dir); 
      if (!fs.existsSync(dirPath)) { 
       fs.mkdirSync(dirPath); 
      } 
     } 
    }); 
    fs.writeFileSync(targetDir, string); 
    console.log(targetDir); 
}); 

這段代碼是從博客:"Angular v4 Universal Demystified"

+0

你想做什麼/實現(太模糊) –

+0

所以你正在建立這些網頁...手動? - main.js做什麼? - 你是否將這些論點轉化爲角度cli?我不完全確定你是否生成最終的html文件 –

+0

是的,這基本上是我的問題,我該怎麼做?我是node.js的新手。思考如何使用所有代碼行來創建數組,但我不知道如何... –

回答

1

有兩種方法,我知道了我的頭頂,專門使用節點(你可以選擇使用一個bash中,Python腳本)

  1. 編輯main.js
  2. 創建它使用childExec一個單獨的script.js

我假設我們可以先編輯main.js(並且稍後用childExec版本更新)。

注:我已刪除了代碼的非相關部,以集中在通過文件名的陣列循環

運行與

節點DIST/main.js DIST/index.html中動態

主要JS

const args = process.argv.slice(2); 
//if (args.length != 3) { 
// process.stdout.write("Usage: node dist/main.js <document> <distDir> <url>\n"); 
// process.exit(); 
//} 

var arr = ['page.html', 'page2.html'] //etc 

arr.forEach(function(file) { 
    renderModuleFactory(AppServerModuleNgFactory, { 
    document: indexFileContent, 
    url: file // -> this is what we need to change page.html 
    }).then(string => { 
    let destUrl = file; // -> page.html 
    if (destUrl == '/') 
     destUrl = 'index.html' 
    const targetDir = args[1] + '/' + destUrl; 
    targetDir.split('/').forEach((dir, index, splits) => { 
     if (index !== splits.length - 1) { 
      const parent = splits.slice(0, index).join('/'); 
      const dirPath = path.resolve(parent, dir); 
      if (!fs.existsSync(dirPath)) { 
       fs.mkdirSync(dirPath); 
      } 
     } 
    }); 
    fs.writeFileSync(targetDir, string); 
    console.log(targetDir); 
    }); 
}); 

釋:

該腳本使用格式node dist/main.js <document> <distDir> <url>渲染文件,因爲我們有文件的聲明arr數組的數組移除arg[2]/<url>。這消除了手動輸入所需文件的需要。