or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdfile-system.mdindex.mdnetwork-operations.mdprocess-management.mdshell-execution.mduser-interaction.mdutilities.md

file-system.mddocs/

0

# File System Operations

1

2

File and directory manipulation utilities for temporary files, directory navigation, and enhanced file system operations.

3

4

## Capabilities

5

6

### Temporary File Operations

7

8

Create temporary files and directories for script operations.

9

10

```typescript { .api }

11

/**

12

* Create a temporary directory

13

* @param prefix - Directory name prefix (default: zx-{randomId})

14

* @param mode - Directory permissions

15

* @returns Absolute path to created directory

16

*/

17

function tempdir(prefix?: string, mode?: Mode): string;

18

19

/**

20

* Create a temporary file

21

* @param name - File name (optional, uses random if not provided)

22

* @param data - Initial file content

23

* @param mode - File permissions

24

* @returns Absolute path to created file

25

*/

26

function tempfile(

27

name?: string,

28

data?: string | Buffer,

29

mode?: Mode

30

): string;

31

32

// Aliases

33

declare const tmpdir: typeof tempdir;

34

declare const tmpfile: typeof tempfile;

35

```

36

37

**Usage Examples:**

38

39

```typescript

40

import { tempdir, tempfile, $ } from "zx";

41

42

// Create temporary directory

43

const tmpDir = tempdir('my-script-');

44

console.log(tmpDir); // /tmp/my-script-abc123

45

46

// Create temporary file with content

47

const configFile = tempfile('config.json', JSON.stringify({

48

environment: 'test',

49

debug: true

50

}));

51

52

// Use in commands

53

await $`cat ${configFile}`;

54

55

// Create temporary file without content

56

const emptyFile = tempfile();

57

await $`echo "data" > ${emptyFile}`;

58

59

// Temporary directory with specific permissions

60

const secureDir = tempdir('secure-', 0o700);

61

```

62

63

### Directory Navigation

64

65

Change working directory and manage directory state.

66

67

```typescript { .api }

68

/**

69

* Change current working directory

70

* @param dir - Directory path or ProcessOutput containing path

71

*/

72

function cd(dir: string | ProcessOutput): void;

73

74

/**

75

* Control directory synchronization behavior

76

* @param flag - Whether to sync process.cwd() with internal state

77

*/

78

function syncProcessCwd(flag?: boolean): void;

79

```

80

81

**Usage Examples:**

82

83

```typescript

84

import { $, cd } from "zx";

85

86

// Change to specific directory

87

cd('/tmp');

88

await $`pwd`; // Shows /tmp

89

90

// Use ProcessOutput

91

const homeDir = await $`echo $HOME`;

92

cd(homeDir);

93

94

// Get current directory

95

const currentDir = await $`pwd`;

96

console.log('Working in:', currentDir.stdout.trim());

97

98

// Temporary directory change

99

const originalDir = process.cwd();

100

cd('/var/log');

101

await $`ls *.log`;

102

cd(originalDir);

103

```

104

105

### Path Utilities

106

107

Node.js path module re-exported for convenience.

108

109

```typescript { .api }

110

/**

111

* Node.js path module with cross-platform path utilities

112

*/

113

export { default as path } from "node:path";

114

```

115

116

**Usage Examples:**

117

118

```typescript

119

import { path, $ } from "zx";

120

121

// Path manipulation

122

const fullPath = path.join('/tmp', 'my-script', 'data.txt');

123

const fileName = path.basename(fullPath); // 'data.txt'

124

const dirName = path.dirname(fullPath); // '/tmp/my-script'

125

const extension = path.extname(fullPath); // '.txt'

126

127

// Cross-platform paths

128

const scriptPath = path.resolve('./scripts/deploy.js');

129

await $`node ${scriptPath}`;

130

131

// Path parsing

132

const parsed = path.parse('/home/user/documents/file.txt');

133

// {

134

// root: '/',

135

// dir: '/home/user/documents',

136

// base: 'file.txt',

137

// ext: '.txt',

138

// name: 'file'

139

// }

140

```

141

142

### Operating System Utilities

143

144

Node.js os module re-exported for system information.

145

146

```typescript { .api }

147

/**

148

* Node.js os module with operating system utilities

149

*/

150

export * as os from "node:os";

151

```

152

153

**Usage Examples:**

154

155

```typescript

156

import { os, $ } from "zx";

157

158

// System information

159

console.log('Platform:', os.platform()); // 'linux', 'darwin', 'win32'

160

console.log('Architecture:', os.arch()); // 'x64', 'arm64'

161

console.log('CPU cores:', os.cpus().length);

162

console.log('Total memory:', os.totalmem());

163

console.log('Free memory:', os.freemem());

164

165

// Temporary directory

166

const tmpDir = os.tmpdir();

167

console.log('System temp dir:', tmpDir);

168

169

// User information

170

console.log('Home directory:', os.homedir());

171

console.log('Username:', os.userInfo().username);

172

173

// Network interfaces

174

const interfaces = os.networkInterfaces();

175

console.log('Network interfaces:', Object.keys(interfaces));

176

177

// Platform-specific operations

178

if (os.platform() === 'win32') {

179

await $`dir`;

180

} else {

181

await $`ls -la`;

182

}

183

```

184

185

### Enhanced File System

186

187

fs-extra module re-exported providing additional file system operations.

188

189

```typescript { .api }

190

/**

191

* Enhanced file system operations (fs-extra)

192

* Includes all Node.js fs methods plus additional utilities

193

*/

194

export { fs } from "./vendor";

195

```

196

197

**Common fs-extra Methods:**

198

199

```typescript { .api }

200

interface FileSystem {

201

// Standard fs methods

202

readFile(path: string, encoding?: BufferEncoding): Promise<string | Buffer>;

203

writeFile(path: string, data: string | Buffer): Promise<void>;

204

readdir(path: string): Promise<string[]>;

205

stat(path: string): Promise<Stats>;

206

207

// Additional fs-extra methods

208

ensureDir(path: string): Promise<void>;

209

ensureFile(path: string): Promise<void>;

210

copy(src: string, dest: string): Promise<void>;

211

move(src: string, dest: string): Promise<void>;

212

remove(path: string): Promise<void>;

213

pathExists(path: string): Promise<boolean>;

214

readJson(path: string): Promise<any>;

215

writeJson(path: string, object: any): Promise<void>;

216

emptyDir(path: string): Promise<void>;

217

}

218

```

219

220

**Usage Examples:**

221

222

```typescript

223

import { fs, $ } from "zx";

224

225

// Ensure directory exists

226

await fs.ensureDir('./build/assets');

227

228

// Copy files

229

await fs.copy('./src', './dist');

230

231

// Check if path exists

232

if (await fs.pathExists('./config.json')) {

233

const config = await fs.readJson('./config.json');

234

console.log('Config:', config);

235

}

236

237

// Write JSON file

238

await fs.writeJson('./output.json', {

239

timestamp: new Date().toISOString(),

240

results: ['success', 'completed']

241

});

242

243

// Clean directory

244

await fs.emptyDir('./temp');

245

246

// Move files

247

await fs.move('./old-location/file.txt', './new-location/file.txt');

248

249

// Remove files/directories

250

await fs.remove('./temporary-files');

251

```

252

253

### Working with ProcessOutput

254

255

Use file system operations with command output.

256

257

**Examples:**

258

259

```typescript

260

import { $, fs, tempfile, path } from "zx";

261

262

// Save command output to file

263

const logOutput = await $`dmesg`;

264

const logFile = tempfile('system.log', logOutput.stdout);

265

266

// Process file listing

267

const fileList = await $`find . -name "*.js"`;

268

const files = fileList.lines();

269

270

for (const file of files) {

271

const stats = await fs.stat(file);

272

console.log(`${file}: ${stats.size} bytes`);

273

}

274

275

// Backup files

276

const timestamp = new Date().toISOString().replace(/:/g, '-');

277

const backupDir = `./backup-${timestamp}`;

278

await fs.ensureDir(backupDir);

279

280

for (const file of files) {

281

const destPath = path.join(backupDir, path.basename(file));

282

await fs.copy(file, destPath);

283

}

284

```

285

286

## Types

287

288

```typescript { .api }

289

/**

290

* File mode permissions (octal number or string)

291

*/

292

type Mode = number | string;

293

294

/**

295

* File system stats object

296

*/

297

interface Stats {

298

isFile(): boolean;

299

isDirectory(): boolean;

300

isSymbolicLink(): boolean;

301

size: number;

302

mtime: Date;

303

ctime: Date;

304

atime: Date;

305

mode: number;

306

uid: number;

307

gid: number;

308

}

309

```