Below is the simple code which I wrote to find the directory of a file
const path = require('path');
console.log("The full loction is :- " , __filename); // Line 1
console.log("The path is :- " , path.dirname(__filename)); // Line 2
console.log(path.dirname('d:\NODEJS\FreeCodeCamp\tempCodeRunnerFile.js')); // Line 3 :- same value as
The output are as follow
The full loction is :- d:\NODEJS\FreeCodeCamp\tempCodeRunnerFile.js
The path is :- d:\NODEJS\FreeCodeCamp
d:
The output image
Now , in Line 3 , I have put same value as __filename as it was in Line 2 but only in string form .Then why the output of path.dirname is different in Line 2 and Line 3.
According to the node.js path documentation it depends on operating system as to how the path is read.
For Windows, it would expect your path to be written like this:
d:\\NODEJS\\FreeCodeCamp\\tempCodeRunnerFile.js
That is (also) because of the way strings work: when you use a \ you're signaling that you're escaping whatever comes after the backslash, so for example \t would be a [tab] character or \n a [newline]. So the string you're giving to the path method sees d:[newline]odejs[somecharacter]reeCodeCamp[tab]empCodeRunnerFile.js, which it then interprets as a weirdly named file located directly in d:, thus the output is correct as only d:.
So to write an actual \ into your string, you need to escape the backslash itself, resulting in \\.
Related
What I tried
'use strict'
const fs = require('fs')
const app = require('express')();
let data = fs.readFileSync('./unichar.txt')
let str = "\u5973\u88DD\u591Away\u9023\u8EAB\u88D9(\u9577\u8896)"
console.log("from file ========> ",data.toString('utf-8'))
console.log("from str variable >>>>>>>>>> ", str)
let buffer = new Buffer(data,'utf-8')
console.log("After some encoding changes ++++++++> ", buffer.toString('utf8'))
app.get('/',(req,res,next)=>{
res.contentType('text/plain')
res.write(data)
res.write(str)
res.end()
next()
})
app.listen(3002)
Output
// from console
$ node index.js
from file ========> \u5973\u88DD\u591Away\u9023\u8EAB\u88D9(\u9577\u8896)
from str variable >>>>>>>>>> 女裝多way連身裙(長袖)
After some encoding changes ++++++++> \u5973\u88DD\u591Away\u9023\u8EAB\u88D9(\u9577\u8896)
// from postman
\u5973\u88DD\u591Away\u9023\u8EAB\u88D9(\u9577\u8896)
女裝多way連身裙(長袖)
// from curl
$ curl localhost:3002
\u5973\u88DD\u591Away\u9023\u8EAB\u88D9(\u9577\u8896)
女裝多way連身裙(長袖)
Problem
I have a problem with unicode text rendering.
For example please consider I have a file with the following single line of unicode characters - \u5973\u88DD\u591Away\u9023\u8EAB\u88D9(\u9577\u8896)
When I read the file using fs module and display the contents it is not rendered as actual characters. It is just displayed as unicode sequences.
Where as when I manually load the same string into a variable and then console that variable, then the actual japanese characters are rendered on the console.
The same problem happens when the same data is send as http response.
Why is the text from file do not get rendered as actual Japanese characters?
I 'am confused and not sure what is to be done to get the file contents display/rendered as actual Japanese characters on console and http response.
It would be very helpful if somebody could please help me to figure out the missing part?
Thankyou
The question seems based on a misunderstanding: The \uxxxx notation cannot be used in text files. In other words: A text file with
\u5973
in it contains six US-ASCII characters, not one Japanese Unicode character.
The \uxxxx notation works only in Javascript, where the statement
fs.writeFileSync("./unichar.txt", "\u5973");
produces a text file with
女
in it.
I have tried to load an image by path that contains special characters like &#^.
When I loaded the image as below, it didn't work.
<img src="file:///test/##$%/0.png"/>
So, I've tried to use encodeURI(path), encodeURIComponent(path), but it didn't work too.
How can I do this?
You have to encode each level in your path (skip the / characters):
const path = 'file:///test/##$%/0.png'
const encodedPath = 'file://' + path.replace('file://', '').split('/').map((p) => encodeURIComponent(p)).join('/')
console.log(encodedPath)
// Output: file:///test/%40%23%24%25/0.png
Use the above output for your img tag, it will be loaded.
You cannot render them as string. If you want to use them, you must write on Numeric code or JS escape.
You can find their codes from here
As your wanted,
# : #
# : #
$ : $
I am having an issue with string.raw. I have the following which works. Example got from : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Development\profile\aboutme.html`;
console.log(`The file was uploaded from: ${filePath}`);
// expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
but when I do the same but only using variable all \ are removed. How can I get the same result as above with using the following code:
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`${"C:\Development\profile\aboutme.html"}`;
console.log(`The file was uploaded from: ${filePath}`);
// expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
but I get "The file was uploaded from: C:Developmentprofileaboutme.html"
Any help is appreciated
How can I get the same result as above with using the following code
You can't, it's different code!
String.raw only works as a tag on template literals. The template literal in your second snippet is `${…}`, i.e. it has no actual content but only one interpolated value. (That value comes from a string literal expression, and String.raw has absolutely no effect on that). It's working the same as
const __temp = "C:\Development\profile\aboutme.html";
// ^ ^ ^
const filePath = String.raw`${__temp}`;
The backlashes there are in a plain "…" string, and not escaped, and there's no way to bring them back.
I use jquery to get the path of out an html img element like this:
path = $("#img_elemnt_id).attr('src')
It gives me a string
path = "C:\User\pic.jpg"
I need to use that string in a function but it only works if the path is like this
path ="C:\\User\\pic.jpg"
Any idea how to do this?
UPDATE: YOUR ANSWERS DO NOT WORK.
path = "C:\\User\\pic.jpg"
works in the function but your answers do not work.
path = "C:\User\pic.jpg"
path = path.replace('\\,'\\\\')
console.log(path)
outputs
C:Userpic.jpg
var path = 'C:\\User\\pic.jpg';
console.log(path);
path = path.replace(/\\/g,'\\\\');
console.log(path);
If path is having single backslash characters, those will be considered as an escape sequence along with the character(s) following them.
The flaw here is that you're declaring your string wrong in the first place:
path = "C:\User\pic.jpg"
console.log(path)
// => C:Userpic.jpg
It's already broken by this point. You must express it correctly in the first
place or the backslash will break things:
path = "C:\\User\\pic.jpg"
console.log(path)
// => C:\User\pic.jpg
This is because \U and \p get interpreted as literal u and p. Beyond that point there is no recovering the "missing" characters because this is how JavaScript's string syntax works. The second version uses \\ which is literal backslash and that avoids the issue.
If you're pulling this from an HTML element it's a different story. The backslashes should be properly encoded if and only if you properly supplied the src attribute in the first place.
If you use file:// path specifiers you can use regular slash instead of backslash and avoid all of this mess which I strongly encourage you to do.
Edit:
Now if you have no control over the src attribute, which is where this should be set properly in the first place, you could try and fix it like:
path = 'path:///' + $('id').attr('src').replace(/\\/, '/');
Use replace
path = path.replace(/\\/g, "\\\\");
I edited to include the global 'g' flag, to make it a correct solution.
I'm using javascript to write a YAML file, but it's invalid.
I'm writing it with one string using \n line breaks:
'dir: ./_data/'+language+'\npath: '+options.path+'\nname: work'
My question is, is this the correct way to break between the vars in a YAML file? It does not seem to validate.
It is difficult to say without knowing what the language and options.path variables are.
This:
dir: ./_data/some_language
path: some_options.path
name: work
is valid YAML, even if you don't have a newline at the end of the file (I recommend to put a \n at the end of your string).
However if the variable options.path starts with a * you'll get an error about an undefined alias. If that value has : (colon + space) in it you'll get an error as well (mapping values not allowed).
You will also get an error if there are spaces before the first key (dir).
So it could generate correct YAML, but it might generate invalid YAML, depending on the values of the variables. The line breaks however, are at the right place.