Home > Software design >  Why My path in Javscript isn't working as expected?
Why My path in Javscript isn't working as expected?

Time:10-30

My path isn't working very well, instead of searching "C:\Users\emanu\OneDrive\Desktop\telegramBOT\data.json" it search "C:UsersemanuOneDriveDesktop elegramBOTdata.json" this is my code (hope it will help):

const editJsonFile = require("edit-json-file");

// If the file doesn't exist, the content will be an empty object by default.
let file = editJsonFile("C:\Users\emanu\OneDrive\Desktop\telegramBOT\data.json");

The path that i am trying to use is a real working path to a json file, i am struggling with this problem...

I tried searching evrywhere but i can't figure it out how to resolve this. This is the error message that the console gives me:

{}
Uncaught Error Error: ENOENT: no such file or directory, open 'C:UsersemanuOneDriveDesktop  elegramBOTdata.json'
    at openSync (fs:600:3)
    at writeFileSync (fs:2221:35)
    at write (c:\Users\emanu\node_modules\edit-json-file\lib\index.js:207:20)
    at save (c:\Users\emanu\node_modules\edit-json-file\lib\index.js:241:18)
    at <anonymous> (c:\Users\emanu\OneDrive\Desktop\telegramBOT\test.js:33:6)
    at Module._compile (internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (internal/modules/cjs/loader:1213:10)
    at Module.load (internal/modules/cjs/loader:1037:32)
    at Module._load (internal/modules/cjs/loader:878:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:23:47)

CodePudding user response:

\ Indicates that the following character should be treated specially, or "escaped". It behaves one of two ways.

  • For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally. For example, /b/ matches the character "b". By placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.

  • For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally. For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches "a*"

To match this character literally, escape it with itself. In other words to search for \ use /\\/.

source MDN

In your case replace

let file = editJsonFile("C:\Users\emanu\OneDrive\Desktop\telegramBOT\data.json");

with

let file = editJsonFile("C:\\Users\\emanu\\OneDrive\\Desktop\\telegramBOT\\data.json");
  • Related