[英]Why doesn't this try and catch work in this case?
I'm learning Node.js but cannot understand why this is not working. 我正在学习Node.js,但无法理解为什么它不起作用。 What is the problem?
问题是什么? Thanks for an answer.
感谢您的回答。
const fs = require('fs')
const path = require('path')
try {
fs.mkdir(path.join(__dirname, '/test'), {}, err => {
console.log(err)
if (err) throw err
})
}
catch (err) {
console.log('file is already created')
}
This is the result: 结果如下:
Error: EEXIST: file already exists, mkdir 'c:\\Users\\stefa\\Desktop\\programming\\learning-node\\playground\\paths\\test'
错误:EEXIST:文件已存在,mkdir'c:\\ Users \\ stefa \\ Desktop \\ programming \\ learning-node \\ playground \\ paths \\ test'
Callback created by lambda expression of err => {/**/}
is ran asynchronously. 由
err => {/**/}
的lambda表达式创建的回调是异步运行的。 try-catch
cannot catch that. try-catch
无法捕捉到。
You should use Promise
s/ Future
s or synchronized version of fs.mkdir
function, fs.mkdirSync
. 您应该使用
Promise
或Future
或fs.mkdir
函数的同步版本fs.mkdirSync
。
Try something like this: 尝试这样的事情:
const fs = require('fs')
const path = require('path')
try {
fs.mkdirSync(path.join(__dirname, '/test'));
}
catch (err) {
console.log('file is already created')
}
or 要么
const fs = require('fs');
const path = require('path');
const util = require('util');
const mkdirPromisifed = util.promisify(fs.mkdir);
(async() {
// ... all other code also should be written in async manner ...
try {
await mkdirPromisifed(path.join(__dirname, '/test'));
}
catch (err) {
console.log('file is already created')
}
}());
As PsychoX said, the callback is called asynchronously . 正如PsychoX所说,回调是异步调用的。
You have a few choices: 您有几种选择:
Just use the callback 只需使用回调
Use the promises-based fs API (or use util.promisify
on mkdir
, but...) 使用基于
util.promisify
的fs API (或在mkdir
上使用util.promisify
,但是...)
(Not recommended) Use the Sync versoin of mkdir
( mkdirSync
) (不推荐)使用Sync versoin of
mkdir
( mkdirSync
)
Here's #1: 这是#1:
const fs = require('fs')
const path = require('path')
fs.mkdir(path.join(__dirname, '/test'), {}, err => {
if (err) {
console.log('file is already created')
return
}
// Do the next thing here
})
Here's #2, using fsPromises.mkdir
: #2,使用
fsPromises.mkdir
:
const fsp = require('fs').promises
const path = require('path')
fsp.mkdir(path.join(__dirname, '/test'))
.then(() => {
// Do the next thing here
})
.catch(err => {
console.log('file is already created')
})
or within an async
function: 或在
async
函数中:
try {
await fsp.mkdir(path.join(__dirname, '/test'))
// Do the next thing here
} catch (err) {
console.log('file is already created')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.