简体   繁体   English

JavaScript、Node.JS:无法读写文本文件(异步、等待问题)

[英]JavaScript, Node.JS : unable to read and write a text file (async, await problem)

I am building a function that edits a PHP file using fs.readFile and fs.writeFile , but the PHP file stays the same.我正在构建一个使用fs.readFilefs.writeFile编辑PHP文件的函数,但PHP文件保持不变。 However, when I run the logic at the main function of the node.js file, it does edit the PHP file.但是,当我在node.js文件的 main 函数中运行逻辑时,它确实编辑了PHP文件。 The following is the code of my function.以下是我的函数的代码。

create_page = async (event) => {
    // edits password.php
    const pwd_pg_loc = '/password.php'

    fs.readFile(pwd_pg_loc, 'utf8', async function (err, data) {
        if (err) return console.log(err)
        const result = await data.replace('$password = \`\`;', '$password= \'1234\';')
        fs.writeFile(pwd_pg_loc, result, 'utf8', function (err) {
            if (err) return console.log(err)
        })
    })
})

I think I have async , await problems here.我想我有asyncawait这里await问题。 Any advise is appreciated!任何建议表示赞赏!

async function (err, data)异步函数(错误,数据)

This looks like you're combining old-school callback semantics (err, data) with Promise semantics.这看起来像是将老式回调语义(err, data)与 Promise 语义相结合。

Probably it should be something like:大概应该是这样的:

const data = await fs.readFile(pwd_pg_loc, 'utf8')

Also:还:

const result = await data.replace(...

There's no need for await here as data.replace is synchronous.这里不需要await ,因为data.replace是同步的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM