Skip to content

Chapter 6: Basic Usage


File Operations

Claude Code provides powerful file operation tools supporting read, write, edit, and more.

Read - Read Files

6.1 文件操作

bash
# Automatically reads relevant files
You: analyze code structure of src/app.js

Claude: [Uses Read tool to read src/app.js]
Reading src/app.js...
This file contains:
- Express app initialization
- 5 route handlers
- Error middleware

Write - Create New Files

bash
You: create a new config file config.yaml

Claude: [Uses Write tool to create file]
 Created config.yaml

Edit - Edit Existing Files

bash
You: change port number in app.js to 4000

Claude: [Uses Edit tool to modify file]
 Updated app.js
  Changed PORT from 3000 to 4000

Glob - Find Files

bash
You: find all JavaScript test files

Claude: [Uses Glob tool]
Found 15 test files:
- src/__tests__/user.test.js
- src/__tests__/auth.test.js
- ...

Grep - Search Content

bash
You: search for all TODO comments in project

Claude: [Uses Grep tool]
Found 8 occurrences of TODO:
- src/api.js:45: // TODO: Add error handling
- src/utils.js:120: // TODO: Optimize performance
- ...

Code Generation

Generate Functions

6.2 代码生成

bash
You: create a function to validate email addresses

Claude: I'll create an email validation function.
javascript
function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

module.exports = { validateEmail };

Generate Classes

bash
You: create a User class with name, email, and validate method

Claude: I'll create a User class with validation.
javascript
class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  validate() {
    if (!this.name || this.name.trim().length === 0) {
      throw new Error('Name is required');
    }
    if (!this.email || !this.email.includes('@')) {
      throw new Error('Valid email is required');
    }
    return true;
  }
}

module.exports = User;

Generate API Endpoints

bash
You: create REST API endpoints for user CRUD operations

Claude: I'll create a complete REST API for user management.
javascript
const express = require('express');
const router = express.Router();

// Create
router.post('/users', async (req, res) => {
  // Implementation
});

// Read all
router.get('/users', async (req, res) => {
  // Implementation
});

// Read one
router.get('/users/:id', async (req, res) => {
  // Implementation
});

// Update
router.put('/users/:id', async (req, res) => {
  // Implementation
});

// Delete
router.delete('/users/:id', async (req, res) => {
  // Implementation
});

module.exports = router;

Code Refactoring

Extract Functions

6.3 代码重构

bash
You: extract validation logic from processOrder into separate function

Claude: I'll extract validation logic into a separate function.

Before:
function processOrder(order) {
  if (!order.items || order.items.length === 0) {
    throw new Error('Order must have items');
  }
  if (!order.customerId) {
    throw new Error('Customer ID required');
  }
  // Process order...
}

After:
function validateOrder(order) {
  if (!order.items || order.items.length === 0) {
    throw new Error('Order must have items');
  }
  if (!order.customerId) {
    throw new Error('Customer ID required');
  }
}

function processOrder(order) {
  validateOrder(order);
  // Process order...
}

Rename Variables

bash
You: rename userData to more meaningful userProfile

Claude: I'll rename userData to userProfile throughout the file.
✓ Renamed 12 occurrences

Convert to ES6

bash
You: convert user.js to ES6 syntax

Claude: Converting to ES6 syntax...

Before:
var User = function(name) {
  this.name = name;
}

User.prototype.getName = function() {
  return this.name;
}

After:
class User {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }
}

Debugging and Testing

Find Bugs

6.4 调试与测试

bash
You: why can't users log in?

Claude: Let me investigate the login issue.

[Reading auth.js...]
[Reading database.js...]

Found the issue:
- Line 45 in auth.js: password comparison using == instead of bcrypt.compare()
- This bypasses password hashing validation

Recommendation:
Replace:
if (user.password == inputPassword)

With:
if (await bcrypt.compare(inputPassword, user.password))

Generate Tests

bash
You: generate unit tests for calculator.js

Claude: I'll create comprehensive unit tests.
javascript
const { add, subtract, multiply, divide } = require('./calculator');

describe('Calculator', () => {
  describe('add', () => {
    it('should add two positive numbers', () => {
      expect(add(2, 3)).toBe(5);
    });

    it('should handle negative numbers', () => {
      expect(add(-2, 3)).toBe(1);
    });
  });

  describe('divide', () => {
    it('should divide two numbers', () => {
      expect(divide(6, 2)).toBe(3);
    });

    it('should throw error for division by zero', () => {
      expect(() => divide(5, 0)).toThrow('Division by zero');
    });
  });
});

Run Tests

bash
You: run all tests

Claude: [Using Bash tool]
$ npm test

 Calculator tests (4/4 passed)
 User tests (8/8 passed)
 API tests (12/12 passed)

Total: 24 tests passed

Git Operations

Check Status

6.5 Git 操作

bash
You: what's the Git status?

Claude: [Running git status]

On branch: main
Changes not staged:
  - modified: src/app.js
  - modified: src/utils.js

Untracked files:
  - src/new-feature.js

Create Commit

bash
You: commit these changes

Claude: I'll create a commit with these changes.

[Adding files...]
$ git add src/app.js src/utils.js src/new-feature.js

[Creating commit...]
$ git commit -m "feat: implement new user authentication feature

- Add JWT token generation
- Update login endpoint
- Add auth middleware

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"

✓ Commit created: abc123def

Create Pull Request

bash
You: create a PR

Claude: I'll create a pull request for this feature.

[Analyzing changes...]
[Pushing to remote...]
$ git push origin feature/auth

[Creating PR...]
$ gh pr create --title "feat: Add user authentication" --body "..."

✓ Pull Request created: #42
https://github.com/user/repo/pull/42

Web Search and Fetch

6.6 Web 搜索与获取

bash
You: what are the new features in React 18?

Claude: [Using WebSearch]
Searching for "React 18 new features"...

Based on search results:
1. Automatic Batching
2. Transitions API
3. Suspense for SSR
4. New Hooks (useId, useTransition, useDeferredValue)
...

Fetch Web Content

bash
You: fetch Next.js official docs about API Routes

Claude: [Using WebFetch]
Fetching: https://nextjs.org/docs/api-routes/introduction

Summary:
- API routes provide backend functionality
- Create files in pages/api directory
- Each file exports a request handler
...

Summary

In this chapter, we learned Claude Code's core toolset:

  • ✅ File operations (Read, Write, Edit, Glob, Grep)
  • ✅ Code generation (functions, classes, APIs)
  • ✅ Code refactoring (extract, rename, convert)
  • ✅ Debugging and testing (find bugs, generate tests, run tests)
  • ✅ Git operations (status, commit, PR)
  • ✅ Web search and fetch

Key Takeaways:

  • Claude intelligently selects appropriate tools
  • Tools can be combined
  • Safety confirmation before operations

Next Step: Chapter 7 introduces MCP servers to extend Claude Code's capabilities!


Content is for learning and research only.