Node.js:如果传递的数据无效,应该拒绝并显示错误。

huangapple go评论125阅读模式
英文:

Node.js: should reject with an error if the passed data is invalid

问题

I'm getting a problem while running the test cases using the node.js application where I'm creating a directory if not exists, writing the json and reading the file.

Here's the Working Demo Link

It's throwing the below error even after handling the error in the code. I didn't get much help from other solutions related to Promise rejection in Stackoverflow. Looking for a working solution. I'm getting the below issue after doing npm test:

  1. should reject with an error if the passed data is invalid:
  2. Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Promise
  3. at TypeError.get (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:385021)
  4. at EventEmitter.emit (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:143926)
  5. at process.onGlobalUncaughtException [as _fatalException] (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:363886)
  6. at triggerUncaughtException (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:42:367400)
  7. at processPromiseRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:1794051)
  8. at processTicksAndRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:801887)
  9. at _0x263935 (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:37:263515)

While doing npm start I'm getting the below problem:

  1. Server running at http://127.0.0.1:3000/
  2. Error: Invalid data
  3. at writeJSON (file:///home/projects/stackblitz-starters-xzxhal/index.js:70:15)
  4. at Server.eval (file:///home/projects/stackblitz-starters-xzxhal/index.js:24:15)
  5. TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Promise
  6. at TypeError.get (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:385021)
  7. at triggerUncaughtException (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:42:367449)
  8. at processPromiseRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:1794051)
  9. at processTicksAndRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:801887)
  10. at _0x263935 (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:37:263515) {
  11. code: 'ERR_INVALID_ARG_TYPE'
  12. }

Here's my index.js file code pieces:

  1. const server = http.createServer(async (req, res) => {
  2. res.statusCode = 200;
  3. res.setHeader('Content-Type', 'text/plain');
  4. const dirPath = DIR_PATH + dirs[0];
  5. const filePath = dirPath + './data.json';
  6. let createdDirectoryIfNotExists = await createDirectoryIfNotExists(filePath);
  7. if (createdDirectoryIfNotExists) {
  8. res.writeHead(200, { 'Content-Type': 'application/json' });
  9. res.write(writeJSON('./temp', contents));
  10. res.end();
  11. }
  12. });
  13. // write json in file
  14. const writeJSON = async (filePath, contents) => {
  15. try {
  16. if (contents && typeof contents === "object") {
  17. const jsonString = JSON.stringify(contents);
  18. // write file
  19. let isWriteFileSynced = fs.writeFileSync(filePath, jsonString, error => {
  20. if (error) {
  21. console.log(error);
  22. } else {
  23. return jsonString;
  24. }
  25. })
  26. if (isWriteFileSynced) {
  27. // read file after file is written
  28. let isReadFileSynced = fs.readFileSync(filePath, "utf8", (error, jsonString) => {
  29. if (error) {
  30. return false;
  31. } else {
  32. return jsonString;
  33. }
  34. })
  35. // if read file, return the jsonString
  36. if (isReadFileSynced) {
  37. return jsonString;
  38. }
  39. } else {
  40. throw new Error("Invalid data");
  41. }
  42. return jsonString;
  43. }
  44. } catch (error) {
  45. console.log(error);
  46. return;
  47. }
  48. };
  49. // create directory if not exists
  50. const createDirectoryIfNotExists = async (path) => {
  51. fs.mkdirSync(path, { recursive: true });
  52. return true;
  53. };

How to solve this issue?

英文:

I'm getting a problem while running the test cases using the node.js application where I'm creating a directory if not exists, writing the json and reading the file.

Here's the Working Demo Link

It's throwing the below error even after handling the error in the code. I didn't get much help from other solutions related to Promise rejection in Stackoverflow. Looking for a working solution. I'm getting the below issue after doing npm test:

  1. should reject with an error if the passed data is invalid:
  2. Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Promise
  3. at TypeError.get (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:385021)
  4. at EventEmitter.emit (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:143926)
  5. at process.onGlobalUncaughtException [as _fatalException] (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:363886)
  6. at triggerUncaughtException (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:42:367400)
  7. at processPromiseRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:1794051)
  8. at processTicksAndRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:801887)
  9. at _0x263935 (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:37:263515)

While doing npm start I'm getting the below problem:

  1. Server running at http://127.0.0.1:3000/
  2. Error: Invalid data
  3. at writeJSON (file:///home/projects/stackblitz-starters-xzxhal/index.js:70:15)
  4. at Server.eval (file:///home/projects/stackblitz-starters-xzxhal/index.js:24:15)
  5. TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Promise
  6. at TypeError.get (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:385021)
  7. at triggerUncaughtException (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:42:367449)
  8. at processPromiseRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:1794051)
  9. at processTicksAndRejections (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:35:801887)
  10. at _0x263935 (https://stackblitzstartersxzxhal-cstc.w-credentialless.staticblitz.com/blitz.a19575a2.js:37:263515) {
  11. code: 'ERR_INVALID_ARG_TYPE'
  12. }

Here's my index.js file code pieces:

  1. const server = http.createServer(async (req, res) => {
  2. res.statusCode = 200;
  3. res.setHeader('Content-Type', 'text/plain');
  4. const dirPath = DIR_PATH + dirs[0];
  5. const filePath = dirPath + './data.json';
  6. let createdDirectoryIfNotExists = await createDirectoryIfNotExists(filePath);
  7. if (createdDirectoryIfNotExists) {
  8. res.writeHead(200, { 'Content-Type': 'application/json' });
  9. res.write(writeJSON('./temp', contents));
  10. res.end();
  11. }
  12. });
  13. // write json in file
  14. const writeJSON = async (filePath, contents) => {
  15. try {
  16. if (contents && typeof contents === "object") {
  17. const jsonString = JSON.stringify(contents);
  18. // write file
  19. let isWriteFileSynced = fs.writeFileSync(filePath, jsonString, error => {
  20. if (error) {
  21. console.log(error);
  22. } else {
  23. return jsonString;
  24. }
  25. })
  26. if (isWriteFileSynced) {
  27. // read file after file is written
  28. let isReadFileSynced = fs.readFileSync(filePath, "utf8", (error, jsonString) => {
  29. if (error) {
  30. return false;
  31. } else {
  32. return jsonString;
  33. }
  34. })
  35. // if read file, return the jsonString
  36. if (isReadFileSynced) {
  37. return jsonString;
  38. }
  39. } else {
  40. throw new Error("Invalid data");
  41. }
  42. return jsonString;
  43. }
  44. } catch (error) {
  45. console.log(error);
  46. return;
  47. }
  48. };
  49. // create directory if not exists
  50. const createDirectoryIfNotExists = async (path) => {
  51. fs.mkdirSync(path, { recursive: true });
  52. return true;
  53. };

How to solve this issue?

答案1

得分: 1

Here is the translated code:

  1. 那个错误来自于`writeJSON`它返回未解决的Promise因此出现了错误
  2. 所以你需要等待它
  3. res.write(await writeJSON('./temp', contents));
  4. 但是正如评论中指出的那样你在函数内部使用了同步方法所以不需要返回Promise也不需要在`writeJSON`函数上使用`async`
  5. 此外`fs.writeFileSync`不接受回调函数它返回`undefined`所以检查部分将始终失败
  6. 它会抛出异常因此你需要将`fs`的两个方法都包装在`try/catch`并从`try`部分返回JSON
  7. 此外不清楚为什么在之后读取文件如果没有抛出异常它就已经被写入了但你可以重新组织一下
  8. 这是一个应该可以工作的起始点在某种程度上):
  9. const writeJSON = (filePath, contents) => {
  10. try {
  11. if (contents && typeof contents === 'object') {
  12. const jsonString = JSON.stringify(contents);
  13. // 写入文件
  14. try {
  15. fs.writeFileSync(
  16. filePath,
  17. jsonString
  18. );
  19. // 文件写入后读取文件
  20. let isReadFileSynced = fs.readFileSync(
  21. filePath,
  22. 'utf8'
  23. );
  24. // 如果读取文件,返回jsonString
  25. if (isReadFileSynced) {
  26. return jsonString;
  27. }
  28. } catch (err) {
  29. console.log(err);
  30. }
  31. } else {
  32. throw new Error('无效的数据');
  33. }
  34. } catch (error) {
  35. console.log(error);
  36. return;
  37. }
  38. };

修订后的测试通过的函数:

  1. const writeJSON = async (filePath, contents) => {
  2. if (contents && typeof contents === 'object') {
  3. const jsonString = JSON.stringify(contents);
  4. // 写入文件
  5. try {
  6. fs.writeFileSync(filePath, jsonString);
  7. // 文件写入后读取文件
  8. let isReadFileSynced = fs.readFileSync(filePath, 'utf8');
  9. // 如果读取文件,返回jsonString
  10. if (isReadFileSynced) {
  11. return jsonString;
  12. }
  13. } catch (err) {
  14. console.log(err);
  15. // 待办事项
  16. throw new Error('写入错误');
  17. }
  18. } else {
  19. throw new Error('无效的数据');
  20. }
  21. };
英文:

That error comes from writeJSON, which returns unresolved Promise, hence the error

So, you need to await it:

  1. res.write(await writeJSON('./temp', contents));

But, as pointed out in the comments, you use sync methods within the function, so no need to return a Promise, so no need to use async on writeJSON function

Also, fs.writeFileSync does not take a callback, and it returns undefined, so the check part will always fail.

It throws, so you need to wrap both fs methods in try/catch, and return json from the try part.

Also, not sure why you read the file afterwards, if it didn't throw, it's written but you can reorganize that:

Here's a starter that should work (somewhat):

  1. const writeJSON = (filePath, contents) => {
  2. try {
  3. if (contents && typeof contents === 'object') {
  4. const jsonString = JSON.stringify(contents);
  5. // write file
  6. try {
  7. fs.writeFileSync(
  8. filePath,
  9. jsonString
  10. );
  11. // read file after file is written
  12. let isReadFileSynced = fs.readFileSync(
  13. filePath,
  14. 'utf8'
  15. );
  16. // if read file, return the jsonString
  17. if (isReadFileSynced) {
  18. return jsonString;
  19. }
  20. } catch (err) {
  21. console.log(err);
  22. }
  23. } else {
  24. throw new Error('Invalid data');
  25. }
  26. } catch (error) {
  27. console.log(error);
  28. return;
  29. }
  30. };

edit

tests passing function:

  1. const writeJSON = async (filePath, contents) => {
  2. if (contents && typeof contents === 'object') {
  3. const jsonString = JSON.stringify(contents);
  4. // write file
  5. try {
  6. fs.writeFileSync(filePath, jsonString);
  7. // read file after file is written
  8. let isReadFileSynced = fs.readFileSync(filePath, 'utf8');
  9. // if read file, return the jsonString
  10. if (isReadFileSynced) {
  11. return jsonString;
  12. }
  13. } catch (err) {
  14. console.log(err);
  15. // todo
  16. throw new Error('err writing');
  17. }
  18. } else {
  19. throw new Error('Invalid Data');
  20. }
  21. };

huangapple
  • 本文由 发表于 2023年6月29日 15:47:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定