nodejs - 临时文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7055061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs - Temporary file name
提问by nornagon
In node.js, how do I generate a unique temporary file name, a la mkstemp(3)? I want to atomically write a file using fs.rename.
在 node.js 中,如何生成唯一的临时文件名 a la mkstemp(3)?我想使用fs.rename.
回答by kinematic
Without using any additional plugins:
不使用任何额外的插件:
var crypto = require('crypto');
var fs = require('fs');
var filename = 'foo'+crypto.randomBytes(4).readUInt32LE(0)+'bar';
fs.writeFileSync(filename, 'baz');
EDIT: read comments.
编辑:阅读评论。
回答by Fernando Carvajal
Try this function, secure and without vulnerabilities. NODE 8.x LTS
试试这个功能,安全无漏洞。节点 8.x LTS
function tempFile (name = 'temp_file', data = '', encoding = 'utf8') {
const fs = require('fs');
const os = require('os');
const path = require('path');
return new Promise((resolve, reject) => {
const tempPath = path.join(os.tmpdir(), 'foobar-');
fs.mkdtemp(tempPath, (err, folder) => {
if (err)
return reject(err)
const file_name = path.join(folder, name);
fs.writeFile(file_name, data, encoding, error_file => {
if (error_file)
return reject(error_file);
resolve(file_name)
})
})
})
}
It resolves the PATH of the temp file, rejects mkdtemp or writeFile errors
它解析临时文件的 PATH,拒绝 mkdtemp 或 writeFile 错误
// C:\Users\MYPC\AppData\Local\Temp\foobar-3HmKod\temp_file
// /temp/Temp/foobar-3HmKod/temp_file
tempFile().then(path => console.log(path)).catch(e => console.log("error", e)) //or
// C:\Users\MYPC\AppData\Local\Temp\foobar-9KHuxg\hola.txt
// /temp/Temp/foobar-9KHuxg/hola.txt
tempFile('hola.txt', 'hello there').then(path => console.log(path)).catch(e => console.log("e", e))
回答by mpen
Similar to kinematic's answer, but with 2 bytes extra entropy and letters instead of numbers:
类似于kinematic 的 answer,但有 2 个字节的额外熵和字母而不是数字:
import Crypto from 'crypto';
import {tmpdir} from 'os';
import Path from 'path';
function tmpFile(ext) {
return Path.join(tmpdir(),`archive.${Crypto.randomBytes(6).readUIntLE(0,6).toString(36)}.${ext}`);
}
Usage:
用法:
const file = tmpFile('tar.gz'); // "/tmp/archive.1scpz5ew5d.tar.gz"
I'm creating archives, so I chose "archive" as the basename, but you can change it as you see fit.
我正在创建档案,所以我选择“档案”作为基本名称,但您可以根据需要更改它。

