我是新的节点,我想使用节点在命令行中循环槽命令。命令看起来像:
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"
有两种我知道的方法,只使用节点(您可以使用bash,python脚本(
- 编辑main.js
- 创建一个使用ChildExec 的单独脚本。
我假设我们可以先编辑main.js(并稍后使用ChildExec版本更新(。
注意:我已经删除了代码的非相关部分,以专注于循环通过文件名
用
运行节点dist/main.js dist/index.html动态
MAIN 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>
。这消除了需要手动键入所需文件的需要。