[英]Error : Path must be a string, NodeJS Read/Write
What i'm trying to do is read/write to multiple files at once, Once a file is created, only the data inside the file would be changed. 我想做的是一次读取/写入多个文件,一旦创建了文件,仅文件内部的数据将被更改。
code: 码:
var files = fs.readdirSync(__dirname+"/")
function readWrite(files) {
fs.readFile(files[i], 'utf-8', function(err, data){
if (err){
console.log(err)
}
fs.writeFile(files[i], 'test string', 'utf-8', function (err) {
if (err){
console.log("completed")
}
})
})
}
for(i in files){
readWrite(files[i])
}
The error is pretty obvious "path must be a string", But how do I go about writing to multiple files in the same directory at once? 该错误非常明显,“路径必须是字符串”,但是如何立即写入同一目录中的多个文件呢?
I'm pretty new to node, so sorry if this seems like a bonehead question, any help would be appreciated. 我对Node非常陌生,所以很抱歉,如果这似乎是一个棘手的问题,我们将不胜感激。
You're passing filename to readWrite function so you should not use [i]
: 您正在将文件名传递给readWrite函数,因此您不应使用
[i]
:
function readWrite(file) {
fs.readFile(file, 'utf-8', function(err, data) {
if (err) {
console.log(err)
}
fs.writeFile(file, 'test string', 'utf-8', function (err) {
if (err) {
console.log("completed")
}
})
})
}
for (i in files) {
readWrite(files[i])
}
Try replacing files[i]
by files
inside your function. 尝试用函数中的
files
替换files[i]
。 You should be using the name of your variable, files
(and probably rename it to filepath
) 您应该使用变量名,
files
(并且可能将其重命名为filepath
)
After that, do you really want to read and write from the same file at the same time (this is what your code is doing) ? 之后,您是否真的要同时从同一文件读取和写入(这就是您的代码在做什么)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.