- Saved searches
- Use saved searches to filter your results more quickly
- how to import css file in node not express #1771
- how to import css file in node not express #1771
- Comments
- Saved searches
- Use saved searches to filter your results more quickly
- License
- nzakas/cssurl
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Загрузка изображений, CSS и JS файлов через NodeJS
- Node.js css-url-parser Parse urls from css file
- More Examples
- Related
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to import css file in node not express #1771
how to import css file in node not express #1771
Comments
hi, I build up http server,
I setting up a router and provide html file and css, js
. head> script> link href=". " script> head>
wrote each above, but, I couldn’t import css and js
how to using external css
The text was updated successfully, but these errors were encountered:
@alipiry
Hello,
first, I really aprociate response
here’s my answer
var exec = require("child_process").exec; var fs = require('fs'); function start(res) console.log("Request handler 'start' was called."); var body = fs.readFileSync('./html/index.html', 'utf8'); res.writeHead(200, "Content-Type": "text/html">); res.write(body); console.log(body); res.end(); > function upload(res) console.log("Request handler 'upload' was called."); res.writeHead(200, "Content-Type": "text/plain">); res.write("Hello Upload"); res.end(); > exports.start = start; exports.upload = upload;
html> head> meta charset pl-s">UTF-8"> style>(./css/index.css)style> head> body> div class pl-s">main"> div class pl-s">main_section_items"> div class pl-s">main_section_item"> h2>환영합니다.h2> p> 공고생의 블로그입니다. p> div> div class pl-s">main_section_item"> div> div> div> body> html>
now, I want to add import external css file on index.html file
I had a lot thing for.
npm install import-css and add
«
» on index.html file
but, there a page except css file..
I want to a personal webpage : )
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
nzakas / cssurl Public archive
A Node.js utility for safely rewriting URLs in CSS code
License
nzakas/cssurl
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
There are many reasons why you would want to systematically replace URLs in CSS code: to convert them into data URIs, to point them to a CDN, to replace a filename with an auto-generated one, and so on. This utility helps by parsing out the URLs in a given string of CSS code and allowing you to replace them with any value you choose. The resulting CSS code is exactly the same as the original except that the URLs have been replaced according to your preferences.
This library contains utilities to help manipulate and change CSS URLs.
The CSS URL rewriter uses a CSS tokenizer to safely find all CSS URLs. This makes any change completely safe because there is no reliance on regular expressions to pull URLs out of CSS.
var URLRewriter = require("cssurl").URLRewriter; var rewriter = new URLRewriter(function(url) // automatically append a query string with a unique value to bust caches return url + "?v pl-c1">+ Date.now(); >); var result = rewriter.rewrite(cssCode);
As the CSS URL rewriter goes through the CSS code, it will call the function passed to the CSSURLRewriter constructor and pass in each URL that it finds. The url is the URL as found in the CSS code with any quotes and surrounding whitespace removed (it does not contain the url() ). You can then inspect the URL, modify it however you want, and return the value you want to use in its place.
The CSS URL Rewriter will only replace URLs represented as URL tokens, that means it must be in the form url(foo.css) and not just «foo.css» , as is allowed in some parts of CSS.
The CSS URL rewrite stream uses the URL rewriter inside of a stream so you can easily pipe code to and from.
var URLRewriteStream = require("cssurl").URLRewriteStream; fs.createReadStream("my.css").pipe(new URLRewriteStream(function(url) // automatically append a query string with a unique value to bust caches return url + "?v pl-c1">+ Date.now(); >)).pipe(fs.createWriteStream("my-new.css"));
The CSS URL translator is a utility that can translate CSS URLs relative to different CSS files. Sometimes you might want to move a CSS file, for example from css/sprites/foo.css to css/sprites.css . When you do that, any relative URLs in the CSS file will no longer be accurate. The CSS URL translator, when used in conjunction with the CSS URL rewriter, makes it easy to make these changes by automatically calculating the new URL path. It’s also smart enough not to translate any non-relative URLs.
var URLTranslator = require("cssurl").URLTranslator; var translator = new URLTranslator(); var result = translator.translate("../../img/foo.png", "css/sprites/foo.css", "css/sprites.css"); console.log(result); // "../img/foo.png"
In order to run tests, clone this repository and then run:
Copyright and License (BSD3)
Copyright 2014 Nicholas C. Zakas. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS «AS IS» AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
About
A Node.js utility for safely rewriting URLs in CSS code
Загрузка изображений, CSS и JS файлов через NodeJS
В статье «Роутинг в NodeJS» был описан способ создания простейшего роутинга в приложении на NodeJS. В этой статье будет доработан предыдущий пример, чтобы выводить изображения, подключить CSS и JavaScript файлы, которые будут выполняться в браузере пользователя.
Проблема в том, что стандартного роутинга (как в nginx или apache) в NodeJS нет, его необходимо запрограммировать. То есть если ввести в адресной строке браузера ссылку на изображение, то страница начнёт бесконечно загружаться:
Потому что в нашем коде ещё не запрограммирована отдача страницы с «Content-Type» равным «image/png». Аналогично и с CSS и JavaScript файлами, которые подключаются для работы в браузере пользователя. Поэтому вспомним код нашего приложения:
let http = require('http'); let fs = require('fs'); http.createServer(function(request, response) < fs.readFile('pages/' + request.url, (error, fileContent) => < response.setHeader('Content-Type' : 'text/html'); if (!error) < // страница существует response.statusCode = 200; response.write(fileContent); response.end(); >else < // страница не найдена fs.readFile('pages/404.html', (error404, fileContent404) =>< if(error404) throw error404; response.statusCode = 404; response.write(fileContent404); response.end(); >); > >); >).listen(80);
Приступим к модификации JS кода приложения. Основная проблема в том, что при запросе к файлу на него выдаётся один и тот же «Content-Type» равный «text/html». Запрограммируем изменение этого заголовка в зависимости от выдаваемого файла с помощью метода «endsWith», который определяет есть ли в конце строки искомая фраза. Получится так:
let http = require('http'); let fs = require('fs'); http.createServer(function(request, response) < fs.readFile('pages/' + request.url, (error, fileContent) => < let contentType = 'text/html'; if (request.url.endsWith('.css')) contentType = 'text/css'; if (request.url.endsWith('.js')) contentType = 'text/javascript'; if (request.url.endsWith('.png')) contentType = 'image/png'; response.setHeader('Content-Type' : contentType); if (!error) < // страница существует response.statusCode = 200; response.write(fileContent); response.end(); >else < // страница не найдена fs.readFile('pages/404.html', (error404, fileContent404) =>< if(error404) throw error404; response.statusCode = 404; response.write(fileContent404); response.end(); >); > >); >).listen(80);
- image/gif: GIF
- image/jpeg и image/pjpeg: JPEG
- image/png: Portable Network Graphics
- image/svg+xml: SVG
- image/tiff: TIFF
- image/vnd.microsoft.icon: ICO
- image/vnd.wap.wbmp: WBMP
- image/webp: WebP
Node.js css-url-parser Parse urls from css file
It ignores duplicated urls and base64 encoded resources.
If no urls found empty array will be returned.
The repository of css-url-parser is in Gitgithub.com/website-scraper/node-css-url-parser
Install Command
To install css-url-parser use the following command:
More Examples
The following examples shows how to use Node.js library css-url-parser.
const getImgSrc = require('get-img-src'); const cheerio = require('cheerio'); const cssUrlParser = require('css-url-parser'); const uniq = require('lodash.uniq'); /**/* w w w . d e m o 2s . c om */ * Find all images referenced in an HTML file and add them to a shared context object. * @param html - Input HTML. * @param file - File path. * @param opts - User options. * @param context - Internal context object. * @returns Unmodified HTML. */ module.exports = (html, file, opts, context) => < // This fetches everywith a src attribute const imageSrcs = getImgSrc(html); // This fetches every url() in a const $ = cheerio.load(html); $('style').each((i, elem) => < const css = elem.children[0].data; imageSrcs.push(. cssUrlParser(css)); >); // This fetches every url() in an inline style $('[style]').each((i, elem) => < const css = $(elem).attr('style'); imageSrcs.push(. cssUrlParser(css)); >); // Store the array here so later steps in the process can access it context.imageSrcs = uniq(imageSrcs); return html; >;
var getCssUrls = require('css-url-parser'); var _ = require('lodash'); var format = require('util').format; function changeExactlyMatchedUrl (text, oldUrl, newUrl) < // starts with ' " ( ends with ' " ) var exactlyMatchedPattern = format('([\'"\\(\\s])%s([\'"\\)\\s])', _.escapeRegExp(oldUrl)); var exactlyMatchedRegexp = new RegExp(exactlyMatchedPattern, 'g'); text = text.replace(exactlyMatchedRegexp, function changeUrl (match, g1, g2) < return g1 + newUrl + g2; >);/* w w w . d e m o 2 s .c o m */ return text; > function CssText (text) < this.text = text || ''; this.paths = getCssUrls(this.text); > CssText.prototype.getPaths = function getPaths () < return this.paths; >; CssText.prototype.updateText = function updateText (pathsToUpdate) < var updatedText = this.text; pathsToUpdate.forEach(function updatePath (path) < updatedText = changeExactlyMatchedUrl(updatedText, path.oldPath, path.newPath); >); return updatedText; >; module.exports = CssText;
var path = require('path') var postcss = require('postcss') var parseCssUrls = require('css-url-parser') var escapeRegexString = require('escape-regex-string') module.exports = postcss.plugin('postcss-mysource-path', mySourcePath) function mySourcePath () < return function transformer (styles, result) < styles.eachDecl(function processDecl (decl) < var urls/*w w w .d e m o 2 s . c o m */ if ( decl.value && decl.value.indexOf('url(') > -1 && (urls = parseCssUrls(decl.value)).length ) < urls .filter(function ignoreAbsolute (url) < return !path.isAbsolute(url) && !isAbsoluteUrl(url) >) .forEach(function processUrl (url) < decl.value = rewriteUrl(decl.value, url) result.messages.push(< plugin: 'postcss-mysource-path', path: url >) >) > >) > > function rewriteUrl (value, url) < var search = new RegExp(escapeRegexString(url) + '(\'|")') return value.replace(search, 'mysource_files/' + path.basename(url) + '$1') > function isAbsoluteUrl (url) < return /^[a-z]+:\/\//.test(url) >
Related
- Node.js shortcss CSS Shorthand expander/combiner.
- Node.js css-rules Install with npm
- Node.js parserlib The ParserLib CSS parser is a CSS3 SAX-inspired parser written in JavaScript.
- Node.js css-url-parser Parse urls from css file
- Node.js parse-import MIT ??
- Node.js parse-css-font Parses the CSS font property.
- Node.js convert-csv-to-json This project is not dependent on others packages or libraries.
demo2s.com | Email: | Demo Source and Support. All rights reserved.