Rob Sked Rob Sked - 26 days ago 10
Node.js Question

Automatize adding/renaming folders in an Express.js app

I'm trying to create a simple Node.js Express website, and I'm running the following commands:

cd node
npm install pug express
express project_name
cd project_name && npm install
npm start


When this runs, it's creating the
/public
folder, along with
/images
,
/javascripts
,
stylesheets
.

Is there a way I can automatically replace these with
/img
,
/js
,
css
when I create it?

I'm simply trying to have a quick set of commands that allow me to create a simplistic Express server.

Answer

Option 1) Bash Script

One way would be to add mv to your list of commands

mv images img      # rename images to img
mv javascripts js  # rename javascripts to js
mv stylesheets css # rename stylesheets to css

which you can then automatize into a simple bash script

my-express.sh

#!/bin/bash 
if [ "$#" == "1" ]; then
  express $1
  cd $1 && npm install
  mv public/images public/img
  mv public/javascripts public/js
  mv public/stylesheets public/css
  npm start
else
  echo "usage my-express <project-name>"
fi

and use it like

./my-express.sh project_name

You might also want to make this script global and give it execution permissions to provide a generic cli tool used like

my-express project_name

Option 2) Node script

Same idea as the bash script except written using node.

#!/usr/bin/env node
var exec = require('child_process').exec;
var projectName = process.argv[2];

var commands = [
  'npm install',
  'mv public/images public/img',
  'mv public/javascripts public/js',
  'mv public/stylesheets public/css',
  'npm start'
];

if (typeof projectName !== 'string' || projectName.length < 1) {
  console.log('Usage: node my-express <project-name>');
} else {
  var cmd = ['express ' + projectName,'cd ' + projectName]
    .concat(commands)
    .join(' && ');

  console.log('Executing\n', cmd.replace(/\&\&/g, '&&\n'));

  exec(cmd, function(error, stdout, stderr) {
    if (error) {
      console.error(error);
    } else {
      console.log(stdout);
    }
  });
}

You also need to create a package.json in the same directory with the following contents

{
  "name": "my-express",
  "version": "0.0.1",
  "bin": {
    "my-express": "./my-express.js"
  }
}

And then run npm install -g which links the script to a location on the path, so you can use it like any other shell command

Usage

my-express my_project

Option 3) Custom express-generator build

Fork the express-generator project and change these 3 lines to what you need them to be

Comments