javascript - 使用nodejs fs 模块将路径添加到文件名中?

标签 javascript node.js

我正在尝试创建一个文件并保存到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;

最佳答案

我相信您传递给fs.writeFile的路径必须是绝对路径。您可以使用 Node 的 native 路径模块将相对路径解析为绝对路径。执行此操作的方法是 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/

相关文章:

node.js - 是否可以将 "next/react + node/express"Web 应用程序部署到一个服务器帐户中,例如 heroku?

node.js - EJS 在某些情况下只输出第一个找到的用户

Javascript 鼠标悬停在动态数量的元素上

javascript - 如何基于 bool 属性有条件地在 ReactJS 中应用嵌套的 SCSS 类?

node.js - 无法连接到 EC2 上的 Postgres : ECONNREFUSED

node.js - Windows Azure Node JS WEBSOCKET 握手失败 503 错误

javascript - Angular2/TypeScript 和 HTTP : How to attach object to component?

javascript - 在变量中存储和检索链接的 jquery 效果/对象

javascript - 用户如何停止选择选择选项而不禁用它

javascript - 在 HTML5 中创建可拖动和可缩放的网格