在Node.js中,我该如何生成一个类似于
mkstemp(3)
的唯一临时文件名?我想使用fs.rename
原子地写入一个文件。mkstemp(3)
的唯一临时文件名?我想使用fs.rename
原子地写入一个文件。另一个广受欢迎的软件包是tmp。
os.tempdir()
方法。在 MacOS 上,这可能会导致问题,因为它返回符号链接而不是绝对路径。 - GROVER.不使用任何额外插件:
var crypto = require('crypto');
var fs = require('fs');
var filename = 'foo'+crypto.randomBytes(4).readUInt32LE(0)+'bar';
fs.writeFileSync(filename, 'baz');
编辑:请阅读评论。
foo1492796329bar
。使用带有随机盐的SHA1会更好。 - Josue Alexander Ibarracrypto.randomBytes(16).toString('base64').replace(/\//,'_')
。根据我的经验,mktemp存在严重的跨平台问题,可能会出现挂起/破坏问题。 - Erik Aronestyconst crypto = require('crypto');
const os = require('os');
const path = require('path');
function tmpFile(prefix, suffix, tmpdir) {
prefix = (typeof prefix !== 'undefined') ? prefix : 'tmp.';
suffix = (typeof suffix !== 'undefined') ? suffix : '';
tmpdir = tmpdir ? tmpdir : os.tmpdir();
return path.join(tmpdir, prefix + crypto.randomBytes(16).toString('hex') + suffix);
}
尝试使用此功能,它是安全的并且没有漏洞。NODE 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)
})
})
})
}
// 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))
与kinematic's 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}`);
}
使用方法:
const file = tmpFile('tar.gz'); // "/tmp/archive.1scpz5ew5d.tar.gz"
readBigInt64LE
)。看起来他们仍然没有添加任意长度的bigint方法,但如果您想要128位,可以分2个块完成。 - mpencrypto.randomBytes(16).toString('hex')
- mpenPath.join(tmpdir(),`${prefix}${Crypto.randomBytes(16).toString('hex')}${suffix}`);}
- Erik Aronesty可以使用内置的库创建临时目录,而不是临时文件。
https://nodejs.org/api/fs.html#fspromisesmkdtempprefix-options
import fs from 'node:fs/promises';
let folder = await fs.mkdtemp('foo-');
在了解你正在工作的位置后,你可以在内部使用常量名称。
使用 npm 包 tempfile
import tempfile from 'tempfile';
或者
let tempfile = "";
import('tempfile').then(a => {
tempfile = a.default;
});
然后:
let filename = tempfile() //e,g: /tmp/5fc8a50f-e9cd-4420-b62a-e365b3ef2c2a
let imagefilename = tempfile(".jpeg") // e,g: /tmp/5a6dea08-a704-4fa8-9d0a-8ffa5e134543.jpeg