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



我有以下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);

该路由被用作Spotify Web API请求的回调,因此我可以获得访问令牌。

Spotify然后重定向到上面的回调函数,你可以在URI中看到它,通过查看";redirect_uri";。

如果您需要有关Spotify授权流程的更多信息,请参阅此处。

这是我用来向Spotify验证我的应用程序的URI。

https://accounts.spotify.com/authorize?client_id=CLIENT_ID&response_type=代码&重定向uri=http://localhost:8888/callback&scope=用户阅读私人%20用户阅读电子邮件%20播放列表修改公共&state=PexBrjEziHepTp7&show_dialog=错误

CLIENT_ID在我提出的请求中被我的真实CLIENT_IID替换

我的问题位于文件编写部分:

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

当Spotify调用回调路由时,我有一个字符串"HELLO";写在我的文本文件中,所以文件编写是有效的。

但即使它已经完成了字符串的写入,Chrome页面仍然在运行,并且"挂起";在服务器上。它运行了几分钟,然后说页面没有发送任何数据而崩溃。为什么

我看了这一页,讨论了使用writeFile和writeFileAsync写入文本文件的方法,但使用这两种方法并没有解决我的问题。

编辑:我真的不想停止Express进程!我只想能够处理另一个请求:(

知道吗?提前感谢:(

如果您的路线没有返回任何东西,请尝试添加res.send({})

在get路由中,如果不发送响应,则无论写入文件是否成功,都必须发送响应。

添加以下代码后写入文件(以及在错误情况下(

res.send({YOUR_CHOICE_RESPONSE_DATA}(

最新更新