nodejs学习-通过命令创建新模板

1.首先安装node,查看node版本

node -V

2.查看npm的版本

npm -V

3.创建模板文件,里面是自己需要的文件,这里是在vue项目中添加的功能,如图

4.重要代码写在nodeCreate.js 中

(1)需要先安装对应的依赖

// gulpjs是一个前端构建工具,而且gulpjs使用的是nodejs中stream来读取和操作数据,其速度更快。
npm install gulp -S 

// 文件重命名
npm install gulp-rename -S

// gulp-replace这是一款gulp3的字符串替换插件
npm install gulp-replace -S

// Inquirer 是常规交互式命令行用户接口的集合,提供给 Node.js 一个方便嵌入,漂亮的命令行接口
npm install inquirer -S 

(2)导入安装好的依赖以及需要的nodejs模块

const gulp = require('gulp');
const inquirer = require('inquirer');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const fs = require('fs'); // 导入文件系统模块(fs)语法
const path = require('path'); // path 模块提供了一些用于处理文件路径的小工具
// child_process 模块提供了以与 popen(3) 类似但不完全相同的方式衍生子进程的能力
const child_process = require('child_process');

(3)先定好询问开发者创建模块信息,可以根据需要添加

let queryPageInfo = async () => {
  let answer2 = await inquirer.prompt([
    {
      type: 'input',
      name: 'name',
      message: 'please input page\'s name ?',
      validate(input) {
        return Boolean(input);
      },
    },
    {
      type: 'input',
      name: 'desc',
      message: 'please input page\'s description ?',
      validate(input) {
        return Boolean(input);
      },
    },
  ]);
  return Object.assign({}, answer2);
};

(4)开始创建文件

let createModule = async info => new Promise((resolve, reject) => {
  console.log(info, '------>>>>>');
  // path.resolve() 方法会把一个路径或路径片段的序列解析为一个绝对路径。
  let dest = path.resolve(`src/view/${info.name}`);
  // child_process.exec()完成后将 stdout 和 stderr 传给回调函数, child_process.exec()的同步版本,其将阻塞 Node.js 事件循环
  child_process.execSync(`mkdir -p ${dest}`);
  // 开始创建
  gulp.src([
    // 正常文件
    `${__dirname}/template/**/*`,
  ])
  // 替换模板内容
  .pipe(replace('{{name}}', info.name))
  .pipe(replace('{{className}}', info.name.replace(/_/g, '-')))
  .pipe(replace('{{desc}}', info.desc))
  .pipe(rename(path => {
    // 只修改文件名
    if (path.extname) {
      path.basename = info.name;
    }
  }))
  .pipe(gulp.dest(dest))
  .on('end', () => {
    // 提示
    console.log(`>>> [${info.name}]文件夹创建完毕,结果在[${dest}]/*中查看`);
    resolve();
  });
});

(5)执行上述方法

// 入口函数
let main = async () => {
  let moduleInfo = await queryPageInfo();
  await createModule(moduleInfo);

  console.log('全部创建任务执行完毕');
};
main().then();

(6)使用node运行,创建新文件

node nodeCreate.js

(7)如果在vue项目中使用还可以在创建文件的时候,把创建的文件,在路由里添加

let registNewRoute = async (answer) => {
  let routePath = `${path.resolve('')}/src/router/index.ts`;
  // 在路由文件里添加这句话,代表如果有这个的话就可以添加最新创建的文件路由,保持新创建的文件路由信息在最后
  let routeTag = `// add new route ..`;
  let routeTel = `{
    path: '/${answer.name}',
    component: () => import('../view/${answer.name}/${answer.name}.vue'),
  },
  ${routeTag}`
  // 异步写入文件内容
  fs.writeFileSync(routePath, fs.readFileSync(routePath, 'utf8').replace(routeTag, routeTel));
}

(8)在Vue项目里的启动方式,可以在package.json里配置

"scripts": {
    "dev": "vite",
    "build": "vite build",
    "create": "node ./src/create/nodeCreate.js" // npm run create,创建新文件
 },

(9)输入npm run create,看效果

 

 

最后,小功能就写好了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用 Node.js 和数据库来渲染 art-template 模板,可以按照以下步骤操作: 1. 安装 Node.js 和相应的数据库驱动程序,比如 MySQL、MongoDB 或 PostgreSQL。 2. 在 Node.js 项目中安装 art-template 和数据库驱动程序的 Node.js 模块,可以使用 npm 命令安装,如下所示: ``` npm install art-template mysql --save ``` 3. 创建数据库连接,使用 Node.js 的数据库驱动程序连接数据库,如下所示: ```javascript const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'my_database' }); connection.connect(); ``` 4. 查询数据库,获取数据并将其传递给 art-template 进行渲染,如下所示: ```javascript const template = require('art-template'); connection.query('SELECT * FROM my_table', function (error, results, fields) { if (error) throw error; const html = template(__dirname + '/views/my_template.art', { data: results }); console.log(html); }); ``` 在此示例中,我们使用 `connection.query()` 方法查询数据库并获取结果。然后,我们将结果传递给 art-template 的 `template()` 方法进行渲染,同时也将模板文件的路径作为第一个参数传递给 `template()` 方法。 在渲染时,我们可以在模板中使用 `data` 变量来访问查询结果中的数据。 5. 关闭数据库连接,如下所示: ```javascript connection.end(); ``` 在 Node.js 中,数据库连接是异步的,因此在完成所有数据库操作后,应该关闭连接,以避免内存泄漏和其他问题。 这样就可以在 Node.js 中使用 art-template 和数据库渲染模板了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值