From fb0523008cf7ad12a447c48e5c69d2979af08af8 Mon Sep 17 00:00:00 2001 From: Naphat Permpredanun <68365175+NaphatPRM@users.noreply.github.com> Date: Tue, 4 Nov 2025 12:26:17 +0700 Subject: [PATCH 1/7] Create a tensorflow document Initiate the format for the tensorflow document based on the pytorch document --- source/_posts/tensorflow.md | 222 ++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 source/_posts/tensorflow.md diff --git a/source/_posts/tensorflow.md b/source/_posts/tensorflow.md new file mode 100644 index 0000000..ad811f5 --- /dev/null +++ b/source/_posts/tensorflow.md @@ -0,0 +1,222 @@ +--- +title: Tensorflow +date: 2025-11-04 +background: bg-[#ffa800] +tags: + - AI + - Python +categories: + - Other +intro: This is a quick reference list of cheat sheets for Tensorflow. See also [PyTorch website](https://pytorch.org/) +--- + +## Imports { .cols-1 } + +### General + +``` +import torch # root package +from torch.utils.data import Dataset, DataLoader # dataset representation and loading +``` + +### Neural Network API + +``` +import torch.autograd as autograd # computation graph +from torch import Tensor # tensor node in the computation graph +import torch.nn as nn # neural networks +import torch.nn.functional as F # layers, activations and more +import torch.optim as optim # optimizers e.g. gradient descent, ADAM, etc. +from torch.jit import script, trace # hybrid frontend decorator and tracing jit +``` + +### Torchscript and JIT + +``` +torch.jit.trace() # takes your module or function and an example + # data input, and traces the computational steps + # that the data encounters as it progresses through the model + +@script # decorator used to indicate data-dependent + # control flow within the code being traced +``` + +### ONNX + +``` +torch.onnx.export(model, dummy data, xxxx.proto) # exports an ONNX formatted + # model using a trained model, dummy + # data and the desired file name + +model = onnx.load("alexnet.proto") # load an ONNX model +onnx.checker.check_model(model) # check that the model + # IR is well formed + +onnx.helper.printable_graph(model.graph) # print a human readable + # representation of the graph +``` + +### Vision + +``` +from torchvision import datasets, models, transforms # vision datasets, + # architectures & + # transforms + +import torchvision.transforms as transforms # composable transforms +``` + +### Distributed Training + +``` +import torch.distributed as dist # distributed communication +from torch.multiprocessing import Process # memory sharing processes +``` + +## Tensors { .cols-1 } + +### Creation + +``` +x = torch.randn(*size) # tensor with independent N(0,1) entries +x = torch.[ones|zeros](*size) # tensor with all 1's [or 0's] +x = torch.tensor(L) # create tensor from [nested] list or ndarray L +y = x.clone() # clone of x +with torch.no_grad(): # code wrap that stops autograd from tracking tensor history +requires_grad=True # arg, when set to True, tracks computation + # history for future derivative calculations +``` + +### Dimensionality + +``` +x.size() # return tuple-like object of dimensions +x = torch.cat(tensor_seq, dim=0) # concatenates tensors along dim +y = x.view(a,b,...) # reshapes x into size (a,b,...) +y = x.view(-1,a) # reshapes x into size (b,a) for some b +y = x.transpose(a,b) # swaps dimensions a and b +y = x.permute(*dims) # permutes dimensions +y = x.unsqueeze(dim) # tensor with added axis +y = x.unsqueeze(dim=2) # (a,b,c) tensor -> (a,b,1,c) tensor +y = x.squeeze() # removes all dimensions of size 1 (a,1,b,1) -> (a,b) +y = x.squeeze(dim=1) # removes specified dimension of size 1 (a,1,b,1) -> (a,b,1) +``` + +### Algebra + +``` +ret = A.mm(B) # matrix multiplication +ret = A.mv(x) # matrix-vector multiplication +x = x.t() # matrix transpose +``` + +### GPU Usage + +``` +torch.cuda.is_available # check for cuda +x = x.cuda() # move x's data from + # CPU to GPU and return new object + +x = x.cpu() # move x's data from GPU to CPU + # and return new object + +if not args.disable_cuda and torch.cuda.is_available(): # device agnostic code + args.device = torch.device('cuda') # and modularity +else: # + args.device = torch.device('cpu') # + +net.to(device) # recursively convert their + # parameters and buffers to + # device specific tensors + +x = x.to(device) # copy your tensors to a device + # (gpu, cpu) +``` + +### Deep Learning + +``` +nn.Linear(m,n) # fully connected layer from + # m to n units + +nn.ConvXd(m,n,s) # X dimensional conv layer from + # m to n channels where X⍷{1,2,3} + # and the kernel size is s + +nn.MaxPoolXd(s) # X dimension pooling layer + # (notation as above) + +nn.BatchNormXd # batch norm layer +nn.RNN/LSTM/GRU # recurrent layers +nn.Dropout(p=0.5, inplace=False) # dropout layer for any dimensional input +nn.Dropout2d(p=0.5, inplace=False) # 2-dimensional channel-wise dropout +nn.Embedding(num_embeddings, embedding_dim) # (tensor-wise) mapping from + # indices to embedding vectors +``` + +### Loss Functions + +``` +nn.X # where X is L1Loss, MSELoss, CrossEntropyLoss + # CTCLoss, NLLLoss, PoissonNLLLoss, + # KLDivLoss, BCELoss, BCEWithLogitsLoss, + # MarginRankingLoss, HingeEmbeddingLoss, + # MultiLabelMarginLoss, SmoothL1Loss, + # SoftMarginLoss, MultiLabelSoftMarginLoss, + # CosineEmbeddingLoss, MultiMarginLoss, + # or TripletMarginLoss +``` + +### Activation Functions + +``` +nn.X # where X is ReLU, ReLU6, ELU, SELU, PReLU, LeakyReLU, + # RReLu, CELU, GELU, Threshold, Hardshrink, HardTanh, + # Sigmoid, LogSigmoid, Softplus, SoftShrink, + # Softsign, Tanh, TanhShrink, Softmin, Softmax, + # Softmax2d, LogSoftmax or AdaptiveSoftmaxWithLoss +``` + +### Optimizers + +``` +opt = optim.x(model.parameters(), ...) # create optimizer +opt.step() # update weights +optim.X # where X is SGD, Adadelta, Adagrad, Adam, + # AdamW, SparseAdam, Adamax, ASGD, + # LBFGS, RMSprop or Rprop +``` + +### Learning rate scheduling + +``` +scheduler = optim.X(optimizer,...) # create lr scheduler +scheduler.step() # update lr after optimizer updates weights +optim.lr_scheduler.X # where X is LambdaLR, MultiplicativeLR, + # StepLR, MultiStepLR, ExponentialLR, + # CosineAnnealingLR, ReduceLROnPlateau, CyclicLR, + # OneCycleLR, CosineAnnealingWarmRestarts, +``` + +## Data Utilities { .cols-1 } + +### Datasets + +``` +Dataset # abstract class representing dataset +TensorDataset # labelled dataset in the form of tensors +Concat Dataset # concatenation of Datasets +``` + +### Dataloaders and DataSamplers + +``` +DataLoader(dataset, batch_size=1, ...) # loads data batches agnostic + # of structure of individual data points + +sampler.Sampler(dataset,...) # abstract class dealing with + # ways to sample from dataset + +sampler.XSampler where ... # Sequential, Random, SubsetRandom, + # WeightedRandom, Batch, Distributed +``` From f3d6ccbd7b8628f363ee9f868b17a9db6ce9b169 Mon Sep 17 00:00:00 2001 From: Naphat Permpredanun <68365175+NaphatPRM@users.noreply.github.com> Date: Tue, 4 Nov 2025 21:55:03 +0700 Subject: [PATCH 2/7] Draft 2 - Tensorflow Editing the initial ideas --- source/_posts/tensorflow.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/source/_posts/tensorflow.md b/source/_posts/tensorflow.md index ad811f5..3bda39b 100644 --- a/source/_posts/tensorflow.md +++ b/source/_posts/tensorflow.md @@ -7,7 +7,8 @@ tags: - Python categories: - Other -intro: This is a quick reference list of cheat sheets for Tensorflow. See also [PyTorch website](https://pytorch.org/) +intro: This is a quick reference list of cheat sheets for Tensorflow. See also [Tensorflow website](https://tensorflow.org/). This docs will +also include the usage of keras for the high-level models --- ## Imports { .cols-1 } @@ -15,8 +16,9 @@ intro: This is a quick reference list of cheat sheets for Tensorflow. See also [ ### General ``` -import torch # root package -from torch.utils.data import Dataset, DataLoader # dataset representation and loading +import tensorflow as tf # root package +import tensorflow_datasets as tfds # dataset representation and loading +tfds.load("mnist") # data here could be ``` ### Neural Network API From 8b0044a33ddde5433d198d6b74a1de30a2c29cf1 Mon Sep 17 00:00:00 2001 From: Naphat Permpredanun <68365175+NaphatPRM@users.noreply.github.com> Date: Sun, 9 Nov 2025 22:52:07 +0700 Subject: [PATCH 3/7] Update tensorflow.md Update contents in tensorflow.md that works parallel with pytorch.md --- source/_posts/tensorflow.md | 224 ++++++++++++++---------------------- 1 file changed, 85 insertions(+), 139 deletions(-) diff --git a/source/_posts/tensorflow.md b/source/_posts/tensorflow.md index 3bda39b..ab38063 100644 --- a/source/_posts/tensorflow.md +++ b/source/_posts/tensorflow.md @@ -7,8 +7,7 @@ tags: - Python categories: - Other -intro: This is a quick reference list of cheat sheets for Tensorflow. See also [Tensorflow website](https://tensorflow.org/). This docs will -also include the usage of keras for the high-level models +intro: This is a quick reference list of cheat sheets for Tensorflow. See also [Tensorflow website](https://tensorflow.org/). --- ## Imports { .cols-1 } @@ -18,71 +17,29 @@ also include the usage of keras for the high-level models ``` import tensorflow as tf # root package import tensorflow_datasets as tfds # dataset representation and loading -tfds.load("mnist") # data here could be -``` - -### Neural Network API - -``` -import torch.autograd as autograd # computation graph -from torch import Tensor # tensor node in the computation graph -import torch.nn as nn # neural networks -import torch.nn.functional as F # layers, activations and more -import torch.optim as optim # optimizers e.g. gradient descent, ADAM, etc. -from torch.jit import script, trace # hybrid frontend decorator and tracing jit -``` - -### Torchscript and JIT - -``` -torch.jit.trace() # takes your module or function and an example - # data input, and traces the computational steps - # that the data encounters as it progresses through the model - -@script # decorator used to indicate data-dependent - # control flow within the code being traced -``` - -### ONNX - -``` -torch.onnx.export(model, dummy data, xxxx.proto) # exports an ONNX formatted - # model using a trained model, dummy - # data and the desired file name - -model = onnx.load("alexnet.proto") # load an ONNX model -onnx.checker.check_model(model) # check that the model - # IR is well formed - -onnx.helper.printable_graph(model.graph) # print a human readable - # representation of the graph -``` - -### Vision - -``` -from torchvision import datasets, models, transforms # vision datasets, - # architectures & - # transforms - -import torchvision.transforms as transforms # composable transforms -``` - -### Distributed Training - -``` -import torch.distributed as dist # distributed communication -from torch.multiprocessing import Process # memory sharing processes +model.compile(optimizer, loss, metrics) # compile necessary components for training and evaluation +model.fit(x_train, y_train, epoch, batch_size) # model training +model.evaluate(x_test, y_test) # model evaluation ``` ## Tensors { .cols-1 } +### Basic Operations +``` +a = tf.constant(5) + tf.constant(3) # tf.constant is an immutable tensor storing the fixed value +a.numpy() # This will return the value, which is 8 +b = tf.Variable(10) # tf.Variable is a shared state for an entire execution time +b.assign(15) # this assign the new value to the variable +with tf.GradientTape() as tape: # record operations on variables for automatic differentiation +``` + ### Creation ``` -x = torch.randn(*size) # tensor with independent N(0,1) entries -x = torch.[ones|zeros](*size) # tensor with all 1's [or 0's] -x = torch.tensor(L) # create tensor from [nested] list or ndarray L +x = +tf.random_normal_initializer(mean, std) # tensor with independent N(mean,stf) entries +tf.random_uniform_initializer(min_val, max_val) # tensor with independent Uniform(min_val, max_val) entries +x = tf.[ones|zeros](*size) # tensor with all 1's [or 0's] y = x.clone() # clone of x with torch.no_grad(): # code wrap that stops autograd from tracking tensor history requires_grad=True # arg, when set to True, tracks computation @@ -92,81 +49,79 @@ requires_grad=True # arg, when set to True, tracks computation ### Dimensionality ``` -x.size() # return tuple-like object of dimensions -x = torch.cat(tensor_seq, dim=0) # concatenates tensors along dim -y = x.view(a,b,...) # reshapes x into size (a,b,...) -y = x.view(-1,a) # reshapes x into size (b,a) for some b -y = x.transpose(a,b) # swaps dimensions a and b -y = x.permute(*dims) # permutes dimensions -y = x.unsqueeze(dim) # tensor with added axis -y = x.unsqueeze(dim=2) # (a,b,c) tensor -> (a,b,1,c) tensor -y = x.squeeze() # removes all dimensions of size 1 (a,1,b,1) -> (a,b) -y = x.squeeze(dim=1) # removes specified dimension of size 1 (a,1,b,1) -> (a,b,1) +tf.shape # shape of the tensor +tf.rank # number of dimension of the tensors +tf.size # number of elements in the tensor? +x = tf.concat(tensor_seq, axis=0) # concatenates tensors along axis +y = tf.reshape(tensor, [new_shape]) # reshapes x into size (a,b,...) +y = tf.reshape(tensor, [(-1,a]) # reshapes x into size (b,a) for some b +y = x.permute(*dims) # permutes dimensions +y = tf.expand_dims(x) # tensor with added axis +y = tf.expand_dims(x, axis=2) # (a,b,c) tensor -> (a,b,1,c) tensor ``` ### Algebra ``` -ret = A.mm(B) # matrix multiplication -ret = A.mv(x) # matrix-vector multiplication -x = x.t() # matrix transpose +tf.add(a, b), a + b # matrix addition +tf.multiply(a, b), a * b # matrix-vector multiplication +tf.matmul(a, b), a @ b # matrix multiplication +tf.transpose() # matrix transpose ``` ### GPU Usage ``` -torch.cuda.is_available # check for cuda -x = x.cuda() # move x's data from - # CPU to GPU and return new object +gpus = tf.config.list_physical_devices('GPU') # check whether there is a GPU usage +if gpus: -x = x.cpu() # move x's data from GPU to CPU - # and return new object +tf.device() # manual device placement + # either "/CPU:0", "/GPU:0", or other qualified name + # of the second GPU of your machine -if not args.disable_cuda and torch.cuda.is_available(): # device agnostic code - args.device = torch.device('cuda') # and modularity -else: # - args.device = torch.device('cpu') # +try: + tf.config.set_visible_devices(gpus[0], 'GPU') # Limiting GPU memory growth -net.to(device) # recursively convert their - # parameters and buffers to - # device specific tensors - -x = x.to(device) # copy your tensors to a device - # (gpu, cpu) -``` - -### Deep Learning ``` -nn.Linear(m,n) # fully connected layer from - # m to n units -nn.ConvXd(m,n,s) # X dimensional conv layer from - # m to n channels where X⍷{1,2,3} - # and the kernel size is s +## Deep Learning Models { .cols-1 } -nn.MaxPoolXd(s) # X dimension pooling layer - # (notation as above) +### Creating Models +``` +tf.keras.Sequential # stack layers in a way that the computation + # will be performed sequentially +``` -nn.BatchNormXd # batch norm layer -nn.RNN/LSTM/GRU # recurrent layers -nn.Dropout(p=0.5, inplace=False) # dropout layer for any dimensional input -nn.Dropout2d(p=0.5, inplace=False) # 2-dimensional channel-wise dropout -nn.Embedding(num_embeddings, embedding_dim) # (tensor-wise) mapping from - # indices to embedding vectors +### Layers + +``` +tf.keras.layers.Dense(m,n) # fully connected layer from + # m to n units + +tf.keras.layers.ConvXd(m,n,s) # X dimensional conv layer from + # m to n channels where X⍷{1,2,3} + # and the kernel size is s + +tf.keras.layers.MaxPoolXd(s) # X dimension pooling layer + # (notation as above) + +tf.keras.layers.BatchNormalization # batch norm layer +tf.keras.layers.RNN/LSTM/GRU # recurrent layers +tf.keras.layers.Dropout(rate=0.5) # dropout layer for any dimensional input +tf.keras.layers.Embedding(input_dim, output_dim) # (tensor-wise) mapping from + # indices to embedding vectors ``` ### Loss Functions ``` -nn.X # where X is L1Loss, MSELoss, CrossEntropyLoss - # CTCLoss, NLLLoss, PoissonNLLLoss, - # KLDivLoss, BCELoss, BCEWithLogitsLoss, - # MarginRankingLoss, HingeEmbeddingLoss, - # MultiLabelMarginLoss, SmoothL1Loss, - # SoftMarginLoss, MultiLabelSoftMarginLoss, - # CosineEmbeddingLoss, MultiMarginLoss, - # or TripletMarginLoss +tf.keras.losses.X # where X is BinaryCrossentropy, BinaryFocalCrossentropy, CTC + # CategoricalCrossentropy, CategoricalFocalCrossentropy, + # CategoricalHinge, CosineSimilarity, Dice, Hinge, Huber + # KLDivergence, LogCosh, MeanAbsoluteError, MeanAbsolutePercentageError + # MeanSquaredError, MeanSquaredLogarithmicError, Poisson + # Reduction, SparseCategoricalCrossentropy, SquaredHinge, Tversky ``` ### Activation Functions @@ -182,22 +137,27 @@ nn.X # where X is ReLU, ReLU6, ELU, SELU, PReLU ### Optimizers ``` -opt = optim.x(model.parameters(), ...) # create optimizer +opt = tf.keras.optimizer.x(model.parameters(), ...) # create optimizer opt.step() # update weights -optim.X # where X is SGD, Adadelta, Adagrad, Adam, - # AdamW, SparseAdam, Adamax, ASGD, - # LBFGS, RMSprop or Rprop +optim.X # where X is SGD, Adadelta, Adafactor, + # Adagrad, Adam, AdamW, Adamax, Ftrl, Lion, + # LossScaleOptimizer ,RMSprop or Rprop ``` -### Learning rate scheduling +### Learning rate scheduling - Callbacks ``` -scheduler = optim.X(optimizer,...) # create lr scheduler -scheduler.step() # update lr after optimizer updates weights -optim.lr_scheduler.X # where X is LambdaLR, MultiplicativeLR, - # StepLR, MultiStepLR, ExponentialLR, - # CosineAnnealingLR, ReduceLROnPlateau, CyclicLR, - # OneCycleLR, CosineAnnealingWarmRestarts, +callbacks = tf.keras.callbacks.LearningRateScheduler(scheduler) # create lr scheduler +model.fit(..., callbacks=[callback], ....) # update lr after optimizer updates weights + # using with fit(), evaluate(), and predict() +``` + +### Saving and Loading Models +``` +tf.keras.models.clone_model(...) # Clone a Functional or Sequential Model instance. +tf.keras.models.load_model(...) # Loads a model saved via model.save(). +tf.keras.models.model_from_json(...) # Parses a JSON model configuration string and returns a model instance. +tf.keras.models.save_model(...) # Saves a model as a .keras file. ``` ## Data Utilities { .cols-1 } @@ -205,20 +165,6 @@ optim.lr_scheduler.X # where X is LambdaLR, MultiplicativeLR, ### Datasets ``` -Dataset # abstract class representing dataset -TensorDataset # labelled dataset in the form of tensors -Concat Dataset # concatenation of Datasets -``` - -### Dataloaders and DataSamplers - -``` -DataLoader(dataset, batch_size=1, ...) # loads data batches agnostic - # of structure of individual data points - -sampler.Sampler(dataset,...) # abstract class dealing with - # ways to sample from dataset - -sampler.XSampler where ... # Sequential, Random, SubsetRandom, - # WeightedRandom, Batch, Distributed +pip install tensorflow-datasets # install the module +tfds.load('mnist', split, shuffle_files) # loading a dataset ``` From 298d0aa678fc04340eec0f9f8a207b2b860275ec Mon Sep 17 00:00:00 2001 From: Naphat Permpredanun <68365175+NaphatPRM@users.noreply.github.com> Date: Sun, 9 Nov 2025 22:58:12 +0700 Subject: [PATCH 4/7] Fixed minor typos --- source/_posts/tensorflow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/_posts/tensorflow.md b/source/_posts/tensorflow.md index ab38063..174a900 100644 --- a/source/_posts/tensorflow.md +++ b/source/_posts/tensorflow.md @@ -127,7 +127,7 @@ tf.keras.losses.X # where X is BinaryCrossentropy, BinaryFocal ### Activation Functions ``` -nn.X # where X is ReLU, ReLU6, ELU, SELU, PReLU, LeakyReLU, +tf.keras.activations.X # where X is ReLU, ReLU6, ELU, SELU, PReLU, LeakyReLU, # RReLu, CELU, GELU, Threshold, Hardshrink, HardTanh, # Sigmoid, LogSigmoid, Softplus, SoftShrink, # Softsign, Tanh, TanhShrink, Softmin, Softmax, From 9d5da6c8a9de1c1300e7758cfecb921b190656f8 Mon Sep 17 00:00:00 2001 From: Marko Schulz Date: Mon, 10 Nov 2025 11:04:07 +0100 Subject: [PATCH 5/7] Remove outdated homebrew command `brew switch` was deprecated in home-brew 2.6.0 and has been removed since then. --- source/_posts/homebrew.md | 1 - 1 file changed, 1 deletion(-) diff --git a/source/_posts/homebrew.md b/source/_posts/homebrew.md index 7b5b228..e54a7c1 100644 --- a/source/_posts/homebrew.md +++ b/source/_posts/homebrew.md @@ -39,7 +39,6 @@ Install Homebrew : | `brew upgrade git` | Upgrade package | | `brew unlink git` | Unlink | | `brew link git` | Link | -| `brew switch git 1.0.0` | Switch package version | | `brew list --versions git` | List the installed versions of package | ### Help From db03ca40e5226f42161c2c1966a141493e5b11ac Mon Sep 17 00:00:00 2001 From: Leonardo-Garzon-1995 Date: Mon, 10 Nov 2025 12:53:12 +0100 Subject: [PATCH 6/7] feat: npm cheatsheet --- source/_posts/npm.md | 95 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 source/_posts/npm.md diff --git a/source/_posts/npm.md b/source/_posts/npm.md new file mode 100644 index 0000000..d639006 --- /dev/null +++ b/source/_posts/npm.md @@ -0,0 +1,95 @@ +--- +title: npm +date: 2020-12-24 17:12:25 +background: bg-[#ebd94e] +tags: + - js + - web + - node + - npm +categories: + - Programming +intro: | + A NPM (node package manager) cheat sheet with the most important concepts, and commands to install, update, and manage your node packages. +plugins: + - copyCode + - runCode +--- + +## Getting Started with npm + +### Introduction + +npm (Node Package Manager) is the default package manager for Node.js. It allows you to install, update, and manage packages (libraries or modules) for your Node.js applications. + +### Installing and checking npm version + +Install Node.js from [nodejs.org](https://nodejs.org/), which includes npm. After installation, you can check the installed version of npm using the following command: + +```bash +npm --version +# or +npm -v +``` + +### Initializing a new project + +```bash +npm init # Interactive setup +# or +npm init -y # Creates a package.json with default values +``` + +## Installing packages + +### Install dependencies from package.json + +```bash +npm install +# or +npm i +``` + +### Install a specific package + +```bash +npm install # Install and add to dependencies +npm install --save-dev # Add to devDependencies +npm install -D # Shorthand for --save-dev +npm install -g # Install globally +npm install @ # Install specific version +npm install @latest # Install latest version +``` + +### Uninstall a package + +```bash +npm uninstall # Uninstall package +npm uninstall -g # Uninstall globally +npm rm # Shorthand for uninstall +``` + +## Viewing, searching and exploring packages + +### Viewing packages + +```bash +npm view # View package details +npm view versions # View all versions of a package +npm view version # View the latest version of a package +npm view description # View the description of a package +``` + +### Searching for packages + +```bash +npm search # Search for packages with similar terms +``` + +### Exploring packages + +```bash +npm docs # Open package documentation in the browser +npm home # Open package homepage in the browser +npm repo # Open package repository in the browser +``` From cb255c70f829cae906a2e51b78f15be9e5cc6d68 Mon Sep 17 00:00:00 2001 From: Leonardo-Garzon-1995 Date: Mon, 10 Nov 2025 15:45:59 +0100 Subject: [PATCH 7/7] feat: npm ceatsheet --- source/_posts/npm.md | 73 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/source/_posts/npm.md b/source/_posts/npm.md index d639006..cf511a0 100644 --- a/source/_posts/npm.md +++ b/source/_posts/npm.md @@ -76,7 +76,7 @@ npm rm # Shorthand for uninstall ```bash npm view # View package details npm view versions # View all versions of a package -npm view version # View the latest version of a package +npm view version # View the latest version of a package npm view description # View the description of a package ``` @@ -93,3 +93,74 @@ npm docs # Open package documentation in the brows npm home # Open package homepage in the browser npm repo # Open package repository in the browser ``` + +## Managing packages + +### Updating packages + +```bash +npm outdated # Check for outdated packages +npm update # Update a specific package +npm update # Update all packages +``` + +### Listing installed packages + +```bash +npm list # List installed packages in the current project +npm list -g # List globally installed packages +npm list --depth=0 # List top-level installed packages only +``` + +### Running scripts + +```bash +npm run # Run a script defined in package.json +npm start # Run the 'start' script +npm test # Run the 'test' script +npm build # Run the 'build' script +``` + +### Cache management + +```bash +npm cache verify # Verify the integrity of the npm cache +npm cache clean # Clear the npm cache +npm cache clean --force # Force clear the npm cache +``` + +### Configuring npm + +```bash +npm config list # List all npm configuration settings +npm config set # Set a configuration value +npm config get # Get the value of a configuration key +npm config delete # Delete a configuration key +``` + +### Auditing and security + +```bash +npm audit # Audit dependencies for vulnerabilities +npm audit fix # Fix vulnerabilities in dependencies +npm audit fix --force # Force fix vulnerabilities, may update major versions +``` + +## Publishing packages + +```bash +npm login # Log in to your npm account (npmjs.com) +npm publish # Publish a package to the npm registry +npm version # Bump the version of your package (e.g., patch, minor, major) +npm unpublish # Unpublish a package (within 72 hours of publishing) +``` + +## Other useful commands + +```bash +npm help # Get general help on npm +npm help # Get help on a specific npm command +npm ci # Install dependencies from package-lock.json (clean install) +npm prune # Remove extraneous packages +npm dedupe # Reduce duplication in the node_modules folder +```