简体   繁体   English

使用 fs.writeFile 写入文本文件后停止执行

[英]Stop execution after writing to text file with fs.writeFile

I have the following Node.JS (ran with Express) code:我有以下 Node.JS(使用 Express 运行)代码:

let app = express();

app.use(cors());

app.get('/callback', function (req, res) {

    // your application requests refresh and access tokens
    // after checking the state parameter

    var code = req.query.code || null;

    var authOptions = {
        url: 'https://accounts.spotify.com/api/token',
        form: {
            code: code,
            redirect_uri: redirectUri,
            grant_type: 'authorization_code'
        },
        headers: {
            'Authorization': 'Basic ' + (new Buffer(clientId + ':' + clientSecret).toString('base64'))
        },
        json: true
    };

    request.post(authOptions, function (error, response, body) {
            if (!error && response.statusCode === 200) {

                var access_token = body.access_token,
                    refresh_token = body.refresh_token;

                fs.writeFile('test.txt', 'HELLO', function (err) {
                    if (err) return console.log(err);
                    console.log('Hello World > helloworld.txt');
                });
            }
        }
    )
});

console.log('Listening on 8888');
app.listen(8888);

The route is used as a callback for a request to the Spotify Web API, thus I can get an access token.该路由用作对 Spotify Web API 的请求的回调,因此我可以获得访问令牌。

Spotify then redirects to the callback function above, you can see it in the URI by looking at "redirect_uri". Spotify 然后重定向到上面的回调 function,您可以通过查看“redirect_uri”在 URI 中看到它。

If you need more information about the Spotify Authorization Flow, see here .如果您需要有关 Spotify 授权流程的更多信息,请参阅此处

Here's the URI I'm using to authenticate my app to Spotify.这是我用来向 Spotify 验证我的应用程序的 URI。

https://accounts.spotify.com/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=http://localhost:8888/callback&scope=user-read-private%20user-read-email%20playlist-modify-public&state=PexBrjEzISHepTp7&show_dialog=false https://accounts.spotify.com/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=http://localhost:8888/callback&scope=user-read-private%20user-read-email%20playlist-modify-public&state=PexBrjEzISHepTp7&show_dialog=false

CLIENT_ID is replaced by my real CLIENT_ID in the request I make在我提出的请求中,CLIENT_ID 被我的真实 CLIENT_ID 替换

My problem is located to the file writing part:我的问题出在文件写入部分:

fs.writeFile('test.txt', 'HELLO', function (err) {
    if (err) return console.log(err);
    console.log('Hello World > helloworld.txt');
});

When the callback route is called by Spotify, I have the string "HELLO" wrote in my text file, so the file writing is functional.当 Spotify 调用回调路由时,我的文本文件中写入了字符串“HELLO”,因此文件写入是有效的。

But even if it has finished writing the string, the Chrome page is still running and "pending" on the server.但即使它已经完成了字符串的写入,Chrome 页面仍在服务器上运行并“挂起”。 It runs for a few minutes and then crash by saying that the page didn't sent any data.它运行了几分钟,然后说页面没有发送任何数据而崩溃。 Why?为什么?

I've looked at this page talking about the methods of writing to text files, using writeFile and writeFileAsync, but using both of them didn't solved my problem.我看过这个页面,讨论了使用 writeFile 和 writeFileAsync 写入文本文件的方法,但同时使用它们并没有解决我的问题。

EDIT: I don't really want to stop the Express process: I just want to be able to process another request :)编辑:我真的不想停止 Express 进程:我只想能够处理另一个请求 :)

Any idea?任何想法? Thanks in advance:)提前致谢:)

You aren't returning anything from your route, try adding res.send({})您没有从您的路线返回任何东西,请尝试添加res.send({})

In your get route you are not sending response, you must send response irrespective of writing a file was successful or not.在您的获取路线中,您没有发送响应,无论写入文件是否成功,您都必须发送响应。

Add below code post writing to file (as well as in if error case)添加以下代码后写入文件(以及在错误情况下)

res.send({YOUR_CHOICE_RESPONSE_DATA}) res.send({YOUR_CHOICE_RESPONSE_DATA})

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

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