Node js windows or linux

Programming Ponderings

Various ponderings about programming topics (and other things of interest).

Tuesday, May 03, 2016

Node.js Hosting – Windows vs. Linux – Case Sensitivity

The Problem

I recently worked on a Node.js project were we were doing our development on Windows 7 machines, but the actual hosting was being done with Cloud Foundry (running Linux). This website contained a number of graphical images, which appeared correctly on our Windows 7 development machines, but when we deployed our application to Cloud Foundry, a number of the images would not appear. The cause for this discrepancy between environments was Linux is a case sensitive operating system, but Windows is not case sensitive.

The Quick Solution

To resolve this issue we went through our code and verify the case of the filenames matched any references to those files in our source code.

Preventing the Issue

We wanted to prevent an issue like this from happening again, so we decided to institute a naming convention for all of our image files. In our case we decided to make them all lower case. To enforce this convention we used the gulp-check-file-naming-convention (see https://github.com/HAKASHUN/gulp-check-file-naming-convention for more details) gulp plugin by HAKASHUN.

The following is a simple gulp example showing how this plugin can be used:

const gulp = require('gulp'); const fileNamingConventionChecker = require("gulp-check-file-naming-convention"); gulp.task('default', function()  gulp.src("./public/**/*") .pipe(fileNamingConventionChecker( caseName: 'lowerCase' >)); >); 

The error message that is generated by this gulp plugin will look something like the following:

[08:27:59] Using gulpfile ~\Source\git\app\gulpfile.js [08:27:59] Starting 'default'. [08:27:59] Finished 'default' after 11 ms events.js:160 throw er; // Unhandled 'error' event ^ Error: Invalid file name at ←[31mC:\Users\NAME\Source\git\app\public \img\SquareProfile.jpg←[39m : > ←[32msquareprofile.jpg←[39m is valid. 

Источник

Выбор между установкой в Windows и подсистеме Windows для Linux

Приступая к работе с JavaScript в Windows 10, первым делом нужно выбрать место для установки платформы: непосредственно в Windows или в подсистеме Windows для Linux (WSL). WSL позволяет запустить любой дистрибутив Linux и использовать командную строку BASH прямо на компьютере с Windows. Ознакомьтесь с дополнительными сведениями о WSL.

Установка в Windows

Если вы не знакомы с разработкой на JavaScript и хотите изучить лишь некоторые основные принципы работы с Node.js, React или Angular, самым быстрым способом начать работу будет установка в Windows. Эти платформы отлично работают в Windows, но в некоторых случаях даже начинающему разработчику требуется установить их в WSL. Например, если вы предпочитаете использовать командную строку Bash для выполнения инструкций из руководства, написанного для пользователей MacOS или Linux, и не хотите усложнять работу поиском эквивалентных команд или установщиков в Windows.

Установка в подсистеме Windows для Linux

Если вы используете платформы на базе JavaScript в рабочих целях, мы рекомендуем выполнить установку в подсистеме WSL, так как она обеспечивает повышенную производительность, совместимость системных вызовов, а также согласованность между локальной средой разработки и средой развертывания (в качестве которой часто используется сервер Linux). В WSL можно использовать рабочие области Linux и не администрировать сценарии сборки одновременно для Linux и Windows. Для запуска контейнеров Docker также лучше использовать WSL. Как правило, с платформами JavaScript лучше всего работает WSL 2 (обновленная версия).

При установке дистрибутива Linux в WSL будет создан каталог \\wsl\Ubuntu-20.04 для хранения файлов (замените Ubuntu-20.04 дистрибутивом Linux, который вы используете). Чтобы открыть этот каталог в Проводнике Windows File Explorer: откройте командную строку WSL, выберите домашний каталог, используя cd ~ , затем введите команду explorer.exe . Будьте внимательны, чтобы избежать сохранение инструментов и файлов в разных системах! Если вы работаете с дистрибутивом Linux устанавливайте, ваши инструменты и средства (NodeJS, диспетчеры пакетов, и т.д.) на свой \\wsl\ диск. НЕТна установленный жесткий диск С ( /mnt/c/Users/yourname$ ). так как это существенно замедлит установку и сборку, а также может вызвать путаницу.

Источник

Should I install on Windows or Windows Subsystem for Linux?

The first decision you will need to make when getting started with JavaScript on Windows is whether to install your chosen framework directly on Windows or on the Windows Subsystem for Linux (WSL). If you’re not familiar with WSL, it enables you to run a Linux distribution of your choice and use a BASH command line right from your Windows machine. Learn more about WSL.

Install on Windows

If you are new to developing with JavaScript and just want to learn some of the basics of working with Node.js, React, or Angular, you can get up and running most quickly by installing directly on Windows. These frameworks will work just fine on Windows, but there may be cases in which even a beginner may want to consider installing on WSL. For example, if you prefer to use a Bash command line in order to follow instructions from a tutorial written for MacOS or Linux users and don’t want to go through the trouble of translating the commands or installers into the Windows equivalent.

Install on Windows Subsystem for Linux

When working with JavaScript-based frameworks in a professional capacity, we recommend WSL as it currently supports better performance speed, system call compatibility, and alignment between your local development environment and deployment environment (which is often a Linux server). WSL enables you to leverage Linux workspaces and avoid having to maintain both Linux and Windows build scripts. Running Docker containers is often a better experience via WSL as well. Specifically, WSL 2 (the updated version) will typically work best with JavaScript frameworks.

Installing a Linux distribution with WSL will create a directory for storing files: \\wsl\Ubuntu-20.04 (substitute Ubuntu-20.04 with whatever Linux distribution you’re using). To open this directory in Windows File Explorer: Open your WSL command line, select your home directory using cd ~ , then enter the command explorer.exe . Be careful not to save your tools and files in different file systems! If you are working in a Linux distribution, install your tools (NodeJS, package managers, etc) on your \\wsl\ drive. NOT on your mounted C drive ( /mnt/c/Users/yourname$ ). Doing so will work, but will significantly slow down your install and build times and may cause confusion.

Источник

Node.js development, windows or linux?

I’m interested in web development on the Node.js platform. My host OS is Windows 7. What would be the preferd way to set up a development environment. Run it directly on the host or in a linux based virtual machine? What are the pros and cons between these two methods? If I go with a VM, can I still run the text editor and web browser in Windows (for performance reasons)?

Just a thought. Some environments run better on linux and vice versa. And some platforms are so complex that you may want to virtualize them. I take it that there’s nothing to gain form virtualizing a Node.js dev environment for small projects?

Running node.js for production might work better on Linux (I honestly don’t know, but it’s a reasonable guess, since it was initially developed on a Unix-y platform). But for development work the «performance» of the user on the desktop is usually much more important than the raw performance of the server environment.

Linux, NodeJS and NPM developer hates Windows and in fact doesn’t use it. He’s not fixing the bugs in this platform.

5 Answers 5

Eh from experience, use Linux Docker.

edit Use Docker. bake in your dependencies, mount your project at run time, pin to a particular version of LTS node only. I’d take a 2gb docker image over un-runnable project leading to days lost being forced to upgrade to new packages. — 2018/04/10

But from someone whose spent the last 8 years developing in a linux based environment, and having spent the last 6 months developing software using nodejs in a windows dot net environment, here are my discoveries, shocking or otherwise.

Problems on windows:

  • can’t effectively utilise docker Latest version of the docker toolkit solves this as far as I’m concerned. ymmv.
  • most node modules require node_gyp, which on the surface doesn’t seem problematic (since gyp is supposed to be cross platform compiler), except when you delve into what it takes to get this working on windows: nothing short of installing visual studio will work. This sucks for me due to several reasons:
  • I’m normally on linux, so I never want to have to use visual studio.
  • It’s entirely the most ridiculous idea that compiling something on windows requires at minimum a 3GB installation of an IDE. not libs but an entirely monolithic piece of GUI software I’ll never ever launch.
  • the windows equivalent of debians build-essentials is actually a disparate sprawling ill named collection of gui only installers scattered across the internet all requiring a specific installation sequence. This, compared to sudo apt-get install build-essentials is overly time consuming and fraught with hidden gotchas.
  • developing on windows will allow you the bad habit of mixed case path names, unless your team either has a strict policy that is followed/enforced this will be a slippery slope to problems later on.
  • while windows supports more than 256 characters in paths, important tooling through out does not. enter stage left: rimraf and robocopy. ugh.
  • the windows terminal sucks. so does the default shell: cmd.exe. Powershell is far too verbose in it’s syntax and not to my taste. Installing Cmder aleviates this somewhat, however the only way for Cmder to interface with cmd.exe is to basically copy keystrokes to a hidden windows terminal running cmd.exe. (lolwut). Cmder works a lot better with shells that a more modular (zsh, bash, etc). . update: I now use powershell with pshazz and scoop, which is actually pleasant to use.
  • Having still improved the shell and terminal situation, nodejs for windows will still assume your environment variables are %OF% %THE% %WINDOWS% %VARIETY%. not the $UNIX $STYLE. So you’ll basically be using bower and npm mostly from cmd.exe. more ugh. I dont’ seem to be having this issue anymore since I’ve incorporated a mix of cross-env and commander or yargs.
    • You’ll also need to install python for windows, not a problem because choco exists and has you back there. update: have a look at boxstarter, will help automate your new machine setup with recipes (or you could actually graduate to using ansible or salt).
    • experienced python, ruby developers will tell you that old projects will need the version of their engine silo’d for when you need to revisit them (upgrading to newer versions is mostly not expedient or practical, read: rabbit holes), so you’ll want something like rvm and virtualenv.
    • nvm (which only works on unix systems linux and macosx) because it’s a collection of bash scripts. I recommend using ZSH as your shell along with Zgen and Tarrasch/zsh-autoenv plugin.
    • nodeenv, which is more likely. a python program that integrates with virtualenv. Some people like this. I have no problem with it, but our team uses nvm.
    • however, you’re better off with nvm-windows because «reasons». scratch that, use nodist on windows. bar far the better choice, you won’t need to worry about some kind of autoenv since nodist by design handles this.

    Installing on Windows:

    1. install chocolatey
    2. choco install cmder nodejs python2 choco install python2
    3. install http://scoop.sh , then use it to install pshazz.
    4. remove any versions of node manually installed globally.
    5. install nvm-windows install nodist.
    6. install visual-studio 2012 express, then never launch it if you treasure your cpu cycles. this may be overkill as microsoft have released an equivalent to build-essentials.
    7. install windows 7/10 64bit sdk

    Problems on Linux:

    tldr; use nvm. for more reasons other than the below.

    • you’ll have to set the global npm node_modules path to a user owned directory (I’ve started using ~/.local/share/npm ). Pleasantly, this is something I found the windows installation of nodejs got right (probably not intentionally). A non issue when using nvm.
    • Ubuntu already has a binary called node , so #!/usr/bin/env node will by default not run nodejs. luckily debian systems have a neat management tool for controlling what the env binary emits: update-alternatives . ignore suggestions to use symlinks here, which will only cause problems later on in subtle ways. also a non issue when using nvm.

    Installing on Linux :

    $ sudo apt-get install git-core git-flow build-essentials python-dev python- pip $ curl https://raw.githubusercontent.com/creationix/nvm/v0.20.0/install.sh | bash $ npm config set prefix ~/.local/share/npm $ nvm install stable $ nvm alias default stable 

    Источник

    Читайте также:  Linux open file browser as root
Оцените статью
Adblock
detector