首页
/ Node.js 临时文件、目录和流支持文档

Node.js 临时文件、目录和流支持文档

2024-12-20 20:50:49作者:农烁颖Land

本文档旨在帮助用户了解和使用 temp 项目,该项目为 Node.js 提供临时文件、目录和流的支持。以下是详细的安装指南、使用说明和 API 文档。

安装指南

要安装 temp 项目,您可以使用 npm:

$ npm install temp

或者,您可以直接从 GitHub 仓库获取:

http://github.com/bruce/node-temp

项目使用说明

temp 项目提供了多种创建临时文件、目录和流的函数,并支持自动清理功能。以下是一些示例:

创建临时文件

使用 openopenSync 函数创建临时文件:

var temp = require('temp'),
    fs   = require('fs'),
    util  = require('util'),
    exec = require('child_process').exec;

temp.track(); // 自动跟踪和清理文件

temp.open('myprefix', function(err, info) {
  if (!err) {
    fs.write(info.fd, "Hello World", (err) => {
      console.log(err);
    });
    fs.close(info.fd, function(err) {
      exec("grep Hello '" + info.path + "'", function(err, stdout) {
        util.puts(stdout.trim());
      });
    });
  }
});

创建临时目录

使用 mkdirmkdirSync 函数创建临时目录:

var temp = require('temp'),
    fs   = require('fs'),
    path = require('path'),
    exec = require('child_process').exec;

temp.track(); // 自动跟踪和清理文件

temp.mkdir('mydir', function(err, dirPath) {
  var filePath = path.join(dirPath, 'example.txt');
  fs.writeFile(filePath, "Hello World", function(err) {
    if (err) throw err;
    exec("cat '" + filePath + "'", function(err, stdout) {
      if (err) throw err;
      console.log(stdout);
    });
  });
});

创建临时流

使用 createWriteStream 函数创建临时流:

var temp = require('temp');

temp.track(); // 自动跟踪和清理文件

var stream = temp.createWriteStream();
stream.write("Hello World");
stream.end();

自定义前缀和后缀

您可以在创建临时文件或目录时提供自定义的前缀和后缀:

var temp = require('temp'),
    fs   = require('fs');

fs.readFile('/path/to/source.pdf', function(err, data) {
  temp.open({suffix: '.pdf'}, function(err, info) {
    if (err) throw err;
    fs.write(info.fd, data, (err) => {
      console.log(err);
    });
    fs.close(info.fd, function(err) {
      if (err) throw err;
      // 进行其他操作
    });
  });
});

项目 API 使用文档

以下是 temp 项目的主要 API:

interface OpenFile {
  path: string;
  fd: number;
}

interface Stats {
  files: number;
  dirs: number;
}

interface AffixOptions {
  prefix?: string;
  suffix?: string;
  dir?: string;
}

function track(value?: boolean): typeof temp;

function mkdir(affixes: string | AffixOptions | undefined, callback: (err: any, dirPath: string) => void): void;
function mkdir(affixes?: string | AffixOptions): Promise<string>;

function mkdirSync(affixes?: string | AffixOptions): string;

function open(affixes: string | AffixOptions | undefined, callback: (err: any, result: OpenFile) => void): void;
function open(affixes?: string | AffixOptions): Promise<OpenFile>;

function openSync(affixes?: string | AffixOptions): OpenFile;

function path(affixes?: string | AffixOptions, defaultPrefix?: string): string;

function cleanup(callback: (err: any, result: Stats) => void): void;
function cleanup(): Promise<Stats>;

function cleanupSync(): boolean | Stats;

function createWriteStream(affixes?: string | AffixOptions): fs.WriteStream;

项目安装方式

请参考安装指南部分。

登录后查看全文
热门项目推荐