简体   繁体   English

fs 完成写入文件后如何运行命令?

[英]How can I run a command once fs is done writing to a file?

Here is the code in question:这是有问题的代码:

        const scriptFiles = fs.readdirSync(scriptsPath)
            .filter(file => file.endsWith(".sql"));

        for (const file of scriptFiles) {

            var data = fs.readFileSync(`${scriptsPath}/${file}`, 'utf8');
            fs.appendFile(`${scriptsPath}/Hotfix.sql`, data.toString() + "\n", (err) => {
                if (err) throw new Error(err)
                console.log('Appending ' + file + '...')
            })

            process.stdout.cursorTo(0);
        }

        console.log(`start ${scriptsPath}/Hotfix.sql`)
        exec(`start ${scriptsPath}/Hotfix.sql`)

The problem that I'm running into is that it is attempting to open/start scriptsPath/Hotfix.sql before anything has been appended to the file.我遇到的问题是它试图在任何内容附加到文件之前打开/启动scriptsPath/Hotfix.sql For example, here is the output from the console.log()s I've added to the script:例如,这是我添加到脚本中的 console.log() 中的 output:

start scriptsPath/Hotfix.sql
Appending file1.sql...    
Appending file2.sql...

is there a way I can have the script wait until the for loop has completed before attempting to execute the command?有没有办法让脚本等到 for 循环完成后再尝试执行命令?

Either use .appendFileSync() and remove the (err)=> callback, or write your code as async entirely.要么使用.appendFileSync()并删除(err)=>回调,要么将代码完全编写为异步。

There is an async version of the fs API, you can access it via require('fs').promises . fs API 有一个异步版本,您可以通过require('fs').promises访问它。

In that case, you will have to use await , your code must be an async function. For an utility script that only does one thing, the benefit of doing it that way is questionable.在这种情况下,您将不得不使用await ,您的代码必须是异步 function。对于只做一件事的实用程序脚本,这样做的好处值得怀疑。

Replace the appendFile() asynchronous method with the appendFileSync() synchronous method so that code waits until the loop has completed.appendFile()异步方法替换为appendFileSync()同步方法,以便代码等待循环完成。

 const scriptFiles = fs.readdirSync(scriptsPath).filter(file => file.endsWith(".sql")); for (const file of scriptFiles) { var data = fs.readFileSync(`${scriptsPath}/${file}`, 'utf8'); fs.appendFileSync(`${scriptsPath}/Hotfix.sql`, data.toString() + "\n"); process.stdout.cursorTo(0); } console.log(`start ${scriptsPath}/Hotfix.sql`) exec(`start ${scriptsPath}/Hotfix.sql`)

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

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