2017-04-24 33 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>。这消除了手动输入所需文件的需要。