Furdew
Furdew

Reputation: 73

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.

Upvotes: 0

Views: 355

Answers (2)

jcubic
jcubic

Reputation: 66470

You're passing filename to readWrite function so you should not use [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])
}

Upvotes: 1

Jerome WAGNER
Jerome WAGNER

Reputation: 22412

Try replacing files[i] by files inside your function. You should be using the name of your variable, files (and probably rename it to 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) ?

Upvotes: 0

Related Questions