visit
For example, if I enter cd ..
in the terminal, Bash will understand that I want to move the current working directory up in one level.
Bash shell is also a programming language and a shell interpreter at the same time, according to this . Bash shell allows users to create and manipulate variables, funtions. Users can also use Bash to execute conditional flow like if...do
, or looping iteration like while...do
just like Javascript.
shell.cd('./subfolder')
This is similar to the cd
command in Bash:
$ cd ./subfolder
const shell = require('shelljs')
shell.mkdir('new-folder')
Initialize a local repository and create an index.js
file:
npm init
touch index.js
In your index.js
files, import the ShellJS library:
const shell = require('shelljs')
We will use the ShellJS's methods cd()
, mkdir()
, touch()
which are very similar to using cd
, mkdir
, and touch
commands in Bash shell.
function createNewFiles() {
//creates a new folder
shell.mkdir('delish-dishes')
//navigate to the new folder directory
shell.cd('./delish-dishes')
//creates two new files: ingredients.txt and recipe.txt
shell.touch(['ingredients.txt', 'recipe.txt'])
}
Then, we will input some content in the newly created text file. Create a new function called writeToNewFiles()
and input the following lines. The echo()
method prints contents to the console, similar to Bash's echo
command. The shell.to()
method behaves similar to the Bash redirect operator /
, which prints the string to the ingredients.txt
file.
function writeToNewFiles() {
//creates a variable that stores a string to be appended to the new file
let fileContent ='Ingredients for fried rice: rice, shallots, scalions, soy sauce, egg, sausage'
//writing the printed string to the ingredients.txt file
shell.echo(fileContent).to('ingredients.txt')
}
createNewFiles()
writeToNewFiles()
node index.js
After running the file, you will see that the ingredients.txt
will contain the newly appended text. A new subfolder named delish-dishes
was also created.
For the full reference of all ShellJS methods and APIs, reference their Github's README.md
file: