在Node中使用'fs'写入文件时出错 [英] Error writing a file using 'fs' in Node

查看:97
本文介绍了在Node中使用'fs'写入文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下功能写入文件:

I'm trying to write to a file using the following function:

function writeFile (data, callback) {
var fs = require('fs');
var now = new Date();

fs.writeFile(now.toISOString() + ".json", data, function(err) {

    if (err) {
        return console.log(err);
    } else {
        console.log(true);
    }
});
}

但是我收到这样的错误:

but im getting an error like this:

{ Error: ENOENT: no such file or directory, open 'C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28\2017_19:47:55.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Me\\WebstormProjects\\blah-blah\\client\\6\\28\\2017_19:47:55.json' }

每次运行程序时,我都试图创建一个文件,但这似乎不能很好地工作,因为它说文件不存在.我有做错什么吗?顺便说一句,即时通讯在Windows上运行

I'm trying to create a file every time I run the program, but that doesn't seem to work very well because it says file does not exist. Is there anything im doing wrong? BTW, im running this on windows

确实是错误的文件名,在保存过程中出现了错误

It was indeed wrong file name that was bugging the saving process

推荐答案

调用 fs.writeFile()时,必须向其传递文件名/路径:

When you call fs.writeFile() you have to pass it a filename/path:

  1. 路径中的父目录已存在的地方.
  2. 路径/文件名仅包含对您的操作系统合法的字符.

除非您已预先创建目录,否则您似乎都可能无法通过这两个操作: C:\ Users \ Ruslan \ WebstormProjects \ communication-system \ client \ 6 \ 28 .而且,如果它在Windows上运行,那么您也不能在文件名中使用:.

It appears you are likely failing both of these unless you've pre-created the directory: C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28. And, if this is running on Windows, then you also can't use : in a filename.

假定您实际上希望路径为 C:\ Users \ Ruslan \ WebstormProjects \ communication-system \ client 以及基于 now.toISOString()<的文件名/code>,通常的解决方法是将路径分隔符和其他无效的文件名字符替换为安全字符,以将 now.toISOString()转换为始终是安全文件名的内容.在这种情况下,您可以这样做:

Assume you actually want the path to be C:\Users\Ruslan\WebstormProjects\communication-system\client and what the filename to be based on your now.toISOString(), the usual work-around is to replace path separators and other invalid filename characters with safe characters to you convert your now.toISOString() to something that is always a safe filename. In this case, you could do this:

// replace forward and back slashes and colons with an underscore
// to make sure this is a legal OS filename
let filename = now.toISOString().replace(/[\/\\:]/g, "_") + ".json";

fs.writeFile(filename, ....)

这篇关于在Node中使用'fs'写入文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆