Skip to content

Instantly share code, notes, and snippets.

@stephane777
Last active March 21, 2020 00:56
Show Gist options
  • Select an option

  • Save stephane777/aee81b4f0c2ff4f140ba9c39139a713e to your computer and use it in GitHub Desktop.

Select an option

Save stephane777/aee81b4f0c2ff4f140ba9c39139a713e to your computer and use it in GitHub Desktop.
## Init package
npm install -y
## Install live server
npm install --save-dev nodemon
or
npm install -D nodemon
## Export a function
const myFunc = (name) => console.log(`Welcome ${name}`);
module.exports = myFunc;
// saved in myFunc.js
## import/require a function
const myFunc = require('./myFunc')
## Function Wrapper
Every file is wrapped in a function which allow us to access all its attributes
//module wrapper function
(function(exports, require, module, __filename, __dirname){
})
## Path
const path = require('path')
// Base filename
console.log(path.basename(__filename))
> index.js
// Directory name
console.log(path.dirname(__filename)
//File Extension
console.log(path.extname(__filename)
//Create path object
console.log(path.parse(__filename)
// Concatename paths
console.log(path.join(__dirname, 'test','hello.html')
// Create directory
fs.mkdir(path.join(__dirname, "test2"), {}, err => {
if (err) throw err;
console.log("Folder created...");
});
// Create and write to file
fs.writeFile(
path.join(__dirname, "test2", "hello.txt"),
"Hello World!",
err => {
if (err) throw err;
console.log("file created and text added...");
appFile();
}
);
const appFile = () => {
fs.appendFile(
path.join(__dirname, "test2", "hello.txt"),
"and I love node js!",
err => {
if (err) throw err;
console.log("text appended...");
}
);
};
// Read data from a file
fs.readFile(path.join(__dirname, '/test','hello.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment