我正在尝试创建一个文件并保存到path
,使用下面的代码将其创建的文件放入记录目录中,但文件名为./app/records/server2b22f465-f7c9-4131- b462-93bc19760ab1.txt
路径包含在文件名中,我缺少什么,所以我只能保存文件名而不将路径保存到记录文件夹中?
main.js
var uuid = require('node-uuid');
var fs = require('fs');
var path = './app/records'
var userLogs = function (data) {
var filename = 'server' + uuid.v4() + '.txt';
var file = path + '/' + filename;
fs.writeFile(file,data,function () {
console.log(file);
});
console.log('userLogs', data);
};
module.exports = userLogs;
最佳答案
我相信您传递给您可以使用 Node 的 native 路径模块将相对路径解析为绝对路径。执行此操作的方法是 fs.writeFile
的路径必须是绝对路径。path.resolve()
。
所以试试这个:
var uuid = require('node-uuid');
var fs = require('fs');
var path = require('path');
var filePath = path.resolve('./app/records');
var userLogs = function (data) {
var filename = 'server' + uuid.v4() + '.txt';
var file = filePath + '/' + filename;
fs.writeFile(file,data,function () {
console.log(file);
});
console.log('userLogs', data);
};
module.exports = userLogs;
编辑:fs.writeFile
不需要绝对路径
根据 Node fs 文档:
https://nodejs.org/api/fs.html#fs_file_system
The relative path to a filename can be used. Remember, however, that this path will be relative to
process.cwd()
关于javascript - 使用nodejs fs 模块将路径添加到文件名中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38490072/