- Windows path in javascript
- Windows vs POSIX
- path.basename(path[, ext])
- path.delimiter
- path.dirname(path)
- path.extname(path)
- path.format(pathObject)
- path.isAbsolute(path)
- path.join([. paths])
- path.normalize(path)
- path.parse(path)
- path.posix
- path.relative(from, to)
- path.resolve([. paths])
- path.sep
- path.win32
- How to determine the OS path separator in JavaScript?
- 5 Answers 5
- The Correct Answer
- The Obvious ‘Duh!’ Question
- What happened!?
- The Solution.
- How can I get the current directory name in Javascript?
- 11 Answers 11
- Node.js — Модуль Path
- Методы
- Fixing npm path in Windows 8 and 10
- 19 Answers 19
- Update:
- You can follow the following steps:
- If you got any error. try the another step:
Windows path in javascript
Стабильность: 2 – Стабильная версия
Модуль path предоставляет утилиты для работы с путями к файлам и директориям. К нему можно получить доступ таким образом:
Windows vs POSIX
По умолчанию операции модуля path варьируются в зависимости от операционной системы, на которой запущено приложение Node.js. Конкретнее, при запуске на Windows модуль path будет подразумевать использование Windows-путей.
Например, использование функции path.basename() с путем к файлу C:\temp\myfile.html , характерным для Windows, будет давать разные результаты при запуске на POSIX и на Windows:
Для получения совместимых результатов при работе с файловыми путями Windows на любой другой операционной системе, нужно использовать path.win32:
На POSIX и Windows:
Для получения совместимых результатов при работе с файловыми путями POSIX на любой другой операционной системе, нужно использовать path.posix:
На POSIX и Windows:
path.basename(path[, ext])
Метод path.basename() возвращает последнюю порцию путей, подобно команде basename на Linux.
Может выпадать ошибка TypeError если path не является строкой или если задается параметр ext , и он не является строкой.
path.delimiter
Предоставляет разделитель пути для конкретной платформы:
Например, на POSIX:
path.dirname(path)
Метод path.dirname() возвращает имя директории path , подобно команде dirname на Linux.
Может выпадать ошибка TypeError если path не является строкой.
path.extname(path)
Метод path.extname() возвращает расширение для path , стоящее после последней точки . , которая означает конец строки в окончании пути. Если точки нет в конце пути или если первый символ базового имени path (см. path.basename() ) является точкой, то возвращается пустая строка.
Выпадает ошибка TypeError если path не является строкой.
path.format(pathObject)
Метод path.format() возвращает строку с путем из объекта. Работает в противоположность path.parse() .
При задании свойств pathObjects , следует помнить, что есть такие комбинации, в которых одно свойство имеет приоритет над другим:
- pathObject.root игнорируется, если есть pathObject.dir
- pathObject.ext и pathObject.name игнорируются, если существует pathObject.base
Пример для POSIX:
path.isAbsolute(path)
Метод path.isAbsolute() определяет, является ли path абсолютным путем.
Если заданный путь path является строкой с нулевой длиной, возвращается false .
Пример для POSIX:
Выпадает ошибка TypeError , если path не является строкой.
path.join([. paths])
Метод path.join() объединяет все данные сегменты пути вместе, используя для этого заданный платформенный разделитель, и приводит полученный путь к нормальному виду.
Нулевой сегмент path игнорируется. Если в результате объединения путей получилась строка с нулевой длиной, тогда возвращается ‘.’ , представляя собой текущую рабочую директорию.
Выпадает ошибка TypeError , если любой из сегментов path не является строкой.
path.normalize(path)
Метод path.normalize() нормализует данный путь, распределяя сегменты ‘..’ и ‘.’
При наличии разделяющих символов для множественных последовательных сегментов пути ( / на POSIX и \ на Windows), они заменяются единственным экземпляром заданного платформой разделителя пути. При этом завершающие разделители сохраняются.
Если путь является строкой с нулевой длиной, возвращается ‘.’ , представляя собой текущую рабочую директорию.
Пример для POSIX:
Выпадает ошибка TypeError , если path не является строкой.
path.parse(path)
Метод path.parse() возвращает объект, чьи свойства представляют собой важные элементы пути.
Возвращаемый объект будет иметь такие свойства:
Например, на POSIX:
Выпадает ошибка TypeError , если path не является строкой.
path.posix
Свойство path.posix предоставляет доступ к заданным реализациям методов path на POSIX.
path.relative(from, to)
Метод path.relative(from, to) возвращает приблизительный путь из from в to . Если from и to приводят к одному и тому же пути (после вызова path.resolve() для обоих), возвращается строка с нулевой длиной.
Если в качестве from или to передается строка с нулевой длиной, вместо таких строк будет использоваться текущая рабочая директория.
Пример для POSIX:
Выпадает ошибка TypeError , если ни from , ни to не являются строками.
path.resolve([. paths])
Метод path.resolve() превращает последовательность путей или сегментов пути в абсолютный путь.
Данная последовательность путей обрабатывается справа налево, добавляя префикс к каждому последующему пути перед компоновкой абсолютного пути. Например, задана последовательность сегментов пути: /foo, /bar, /baz , вызов path.resolve(‘/foo’, ‘/bar’, ‘baz’) возвратит /bar/baz .
Если после обработки все данные сегменты абсолютного пути не были сгенерированы, используется текущая рабочая директория.
Путь, полученный в результате, нормализуется и слэши, завершающие его, удаляются, но только если путь не был превращен в путь к корневой директории.
Сегменты нулевого пути игнорируются.
Если не передается сегментов пути, path.resolve() возвращает абсолютный путь к текущей рабочей директории.
Выпадает ошибка TypeError , если любой из аргументов не является строкой.
path.sep
Предоставляет заданный платформой разделитель сегментов пути:
path.win32
Свойство path.win32 предоставляет доступ к заданным реализациям методов path на Windows.
Примечание: на Windows оба слэша – прямой (/) и обратный (\) принимаются как разделители пути, однако, в возвращаемых значениях используется только обратный слэш.
How to determine the OS path separator in JavaScript?
How can I tell in JavaScript what path separator is used in the OS where the script is running?
5 Answers 5
Afair you can always use / as a path separator, even on Windows.
So, the situation can be summed up rather simply:
All DOS services since DOS 2.0 and all Windows APIs accept either forward slash or backslash. Always have.
None of the standard command shells (CMD or COMMAND) will accept forward slashes. Even the «cd ./tmp» example given in a previous post fails.
Use path module in node.js returns the platform-specific file separator.
example
Edit: As per Sebas’s comment below, to use this, you need to add this at the top of your js file:
The Correct Answer
Yes all OS’s accept CD ../ or CD ..\ or CD .. regardless of how you pass in separators. But what about reading a path back. How would you know if its say, a ‘windows’ path, with ‘ ‘ and \ allowed.
The Obvious ‘Duh!’ Question
What happens when you depend on, for example, the installation directory %PROGRAM_FILES% (x86)\Notepad++ . Take the following example.
What happened!?
targetDir is being set to a substring between the indices 0 , and 0 ( indexOf(‘/’) is -1 in C:\Program Files\Notepad\Notepad++.exe ), resulting in the empty string.
The Solution.
Server side detection of OS.
Browser side detection of OS
Helper Function to get the separator
Helper function to get the parent directory (cross platform)
getDir() must be intelligent enough to know which its looking for.
You can get even really slick and check for both if the user is inputting a path via command line, etc.
How can I get the current directory name in Javascript?
I’m trying to get the current directory of the file in Javascript so I can use that to trigger a different jquery function for each section of my site.
11 Answers 11
window.location.pathname will get you the directory, as well as the page name. You could then use .substring() to get the directory:
Hope this helps!
In Node.js, you could use:
You can use window.location.pathname.split(‘/’);
That will produce an array with all of the items between the /’s
This will work for actual paths on the file system if you’re not talking the URL string.
To return without the trailing slash, do:
complete URL
If you want the complete URL e.g. http://website/basedirectory/workingdirectory/ use:
local path
If you want the local path without domain e.g. /basedirectory/workingdirectory/ use:
In case you don’t need the slash at the end, remove the +1 after location.lastIndexOf(«/»)+1 .
directory name
If you only want the current directory name, where the script is running in, e.g. workingdirectory use:
This one-liner works:
Assuming you are talking about the current URL, you can parse out part of the URL using window.location . See: http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript
If you want the complete URL e.g. website.com/workingdirectory/ use: window.location.hostname+window.location.pathname.replace(/[^\\\/]*$/, »);
An interesting approach to get the dirname of the current URL is to make use of your browser’s built-in path resolution. You can do that by:
- Create a link to . , i.e. the current directory
- Use the HTMLAnchorElement interface of the link to get the resolved URL or path equivalent to . .
Here’s one line of code that does just that:
In contrast to some of the other solutions presented here, the result of this method will always have a trailing slash. E.g. running it on this page will yield /questions/3151436/ , running it on https://stackoverflow.com/ will yield / .
It’s also easy to get the full URL instead of the path. Just read the href property instead of pathname .
Node.js — Модуль Path
Дата публикации: 2017-12-26
От автора: модуль Node js path используется для обработки и преобразования путей к файлам. Этот модуль можно импортировать, используя следующий синтаксис.
Методы
path.normalize(р) — Нормализует строковый путь, обрабатывая «..» и «.».
Бесплатный курс «NodeJS. Быстрый старт»
Изучите курс и узнайте, как создать веб-приложение с нуля на JavaScript с NodeJS
path.join([path1][, path2][, . ]) — Объединяет все аргументы и нормализует полученный путь.
path.resolve([from . ], to) — Обрабатывает абсолютный путь.
path.isAbsolute(path) — Определяет, является ли путь абсолютным. Абсолютный путь всегда будет обрабатываться в том же месте, независимо от рабочего каталога.
path.relative(from, to) — Обрабатывает относительный от from до to.
path.dirname(p) — Возвращает имя директории для заданного пути. Подобно команде dirname в Unix.
path.basename(p[, ext]) — Возвращает последнюю часть пути. Подобно команде basename в Unix.
path.extname(p) — Возвращает из пути расширение последней части, начиная от последней ‘.’ до конца строки. Если ‘.’ не встречается в последней части пути или в его начале, возвращает пустую строку.
path.parse(pathString) — Возвращает объект из строки пути.
path.format(pathObject) — Возвращает строку пути из объекта, противоположно path.parse, описанному выше.
Бесплатный курс «NodeJS. Быстрый старт»
Изучите курс и узнайте, как создать веб-приложение с нуля на JavaScript с NodeJS
Fixing npm path in Windows 8 and 10
Have done a lot of googling, tried reinstalling node.js using the official installer, but my npm pathing still doesn’t work.
This doesn’t work
I get an error message saying missing module npm-cli.js
2 hours of googling later I discovered a workaround
Instead of simply ‘npm‘ I type
But how can I correct my nodejs install so I can simply type ‘npm’ ?
19 Answers 19
You need to Add C:\Program Files\nodejs to your PATH environment variable. To do this follow these steps:
- Use the global Search Charm to search «Environment Variables»
- Click «Edit system environment variables»
- Click «Environment Variables» in the dialog.
- In the «System Variables» box, search for Path and edit it to include C:\Program Files\nodejs . Make sure it is separated from any other paths by a ; .
You will have to restart any currently-opened command prompts before it will take effect.
get the path from npm:
npm config get prefix
and just as a future reference, this is the path I added in Windows 10:
Update:
If you want to add it for all users just add the following path [by @glenn-lawrence from the comments]:
I have used the cmdlet and navigate to the path you want to switch your npm files to. Type in npm root -g to see what the current path your npm is installed to. Next use npm config set prefix and your npm path will be changed to whatever directory you are currently on.
Go to control panel -> System -> Advanced System Settings then environment variables.
From here find the path variable, Go to the end of the line and paste «C:\Program Files\nodejs\node_modules\npm\bin» (change the path to the directory to where ever you installed it e.g. if you specifically installed it anywhere change it)
Try this one dude if you’re using windows:
1.) Search environment variables at your start menu’s search box.
2.) Click it then go to Environment Variables.
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:\Program Files\nodejs\node_modules\npm\bin
If you got an error. Do the number 4.) Click New, then browse the bin folder
- You may also Visit this link for more info.
Edit the System environment variables, and enter following path:
Installed Node Version Manager (NVM) for Windows: https://github.com/coreybutler/nvm-windows
I’m using Windows 10 — 64 bit so I run. Commands:
- nvm arch 64 (to make default the 64 bit executable)
- nvm list (to list all available node versions)
- nvm install 8.0.0 (to download node version 8.0.0 — you can pick any)
- nvm use 8.0.0 (to use that specific version)
In my case I had to just switch to version 8.5.0 and then switch back again to 8.0.0 and it was fixed. Apparently NVM sets the PATH variables whenever you do that switch.
You can follow the following steps:
- Search environment variables from start menu’s search box.
- Click it then go to Environment Variables
- Click PATH
- click Edit
- Click New and try to copy and paste your path for ‘bin‘ folder [find where you installed the node] for example according to my machine ‘ C:\Program Files\nodejs\node_modules\npm\bin ‘
If you got any error. try the another step:
- Click New, then browse for the ‘bin‘ folder
This worked for me: 1. npm root -g (to see the current npm is installed) 2. npm config set prefix (to change the path)
change the path for nodejs in environment varibale.
I did this in Windows 10,
- Search for Environment Variables in the Windows search
- «Edit the System environment variables» option will be popped in the result
- Open that, select the «Path» and click on edit, then click «New» add your nodeJS Bin path i.e in my machine its installed in c:\programfiles\nodejs\node_modules\npm\bin
- Once you added click «Ok» then close
Now you can write your command in prompt or powershell.
If you using WIndows 10, go for powershell its a rich UI
If after installing your npm successfully, and you want to install VueJS then this is what you should do
after running the following command (as Admin)
npm install —global vue-cli
It will place the vue.cmd in the following directory C:\Users\YourUserName\AppData\Roaming\npm
you will see this in your directory.
Now to use vue as a command in cmd. Open the cmd as admin and run the following command.
setx /M path «%path%;%appdata%\npm»
Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.
I hope this helps.
steps 1 in the user variable and system variable
then check both node -v and the npm -v then try to update the the npm i -g npm
I’ve had this issue in 2 computers in my house using Windows 10 each. The problem began when i had to change few Environmental variables for projects that I’ve been working on Visual studio 2017 etc. After few months coming back to using node js and npm I had this issue again and non of the solutions above helped. I saw Sean’s comment on Yar’s solution and i mixed both solutions: 1) at the environmental variables window i had one extra variable that held this value: %APPDATA%\npm. I deleted it and the problem dissapeared!