what does the filename option do in stylus.render function? - node.js

I have tried to change the filename parameter as per the sample codes (from official documentation) given below but it does not have any impact on my output.
I would expect that the filename would specify the path to either input or the output. However str is the input and needs to be defined and no output file gets generated based on the filename parameter.
So what does the filename option do in stylus.render function ?
Sample code from
var css = require('../')
, str = require('fs').readFileSync(__dirname + '/basic.styl', 'utf8');
css.render(str, { filename: 'basic.styl' }, function(err, css){
if (err) throw err;
console.log(css);
});
Sample code from
var stylus = require('stylus');
stylus.render(str, { filename: 'nesting.css' }, function(err, css){
if (err) throw err;
console.log(css);
});

The filename parameter is used in error reporting, not as an input or output filename.
From the docs at http://learnboost.github.io/stylus/docs/js.html:
Simply require the module, and call render() with the given string of Stylus code, and (optional) options object.
Frameworks utilizing Stylus should pass the filename option to provide better error reporting.

Related

sharp constructor won't take a variable as file path input when try to resize image - [input file missing error]

it is quite strange that when passing a String variable to sharp() as file path input always gives me this error -
[Error: Input file is missing or of an unsupported image format]
I even add toString() to my variable so my return is for sure a string.
var tmp = 'image/'+ id + '.jpg';
var path = tmp.toString();
console.log("What's in tmp: " + tmp);
console.log("What's in path: " + path);
sharp(path)
.resize(300, 300)
.toFile('image/'+ id + 'L.jpg', function(err, info) {
if (err) {
console.log('Error Type: ', err);
}
});
The way I verified my code is following:
It works the other way so my image format is correct. I even do a 'sharp.format' to confirm its support so it's not the problem here. Next I copy the 'path' variable string from my console log output and paste it directly inside sharp constructor call = sharp().
Console OUTPUT:
What's in a tmp: image/1.jpg
What's in a path: image/1.jpg
sharp('image/1.jpg')
.resize(300, 300)
.toFile('image/'+ id + 'L.jpg', function(err, info) {
if (err) {
console.log('Error Type: ', err);
}
});
Now everything starts working again - file is resized and generated in image. Switching back using 'path' variable continue gives me no luck. It surprises me with this kind of issue because it clearly stated in their document that it supports a String type input. Also now I'm confused with the difference between path and 'image/1.jpg'. Maybe my next step is to use ( path === 'image/1.jpg' ) to compare them.
Statement from sharp doc for your reference -->
'input (Buffer | String)? or a String containing the path to an JPEG, PNG, WebP, GIF, SVG or TIFF image file.'
It must be something obvious I missed. I am sure that when they design the tool, they give user the flexibility to define their input path as a variable for code reuse. So any suggestion? Thanks in advance.

Add string on top file with NodeJS

I would like add string on the top of my js file. Actuly, it's on the end :
var file = './public/js/app.bundleES6.js',
string = '// My string';
fs.appendFileSync(file, string);
Do you have idea for add my string on the first line ?
Thank you !
I think there is no built-in way to insert at the beginning of the file in Node.js.
But you can use readFileSync and writeFile methods of fs to resolve this issue
It will append string at top of the file
Try this
Method#1
var fs = require('fs');
var data = fs.readFileSync('./example.js').toString().split("\n");
data.splice(0, 0, "Append the string whatever you want at top" );
var text = data.join("\n");
fs.writeFile('./example.js', text, function (err) {
if (err) return err;
});
Method#2
If you are relying on to use third party module then you can use prepend module to add the string at the top as suggested by #robertklep.
var prepend = require('prepend');
prepend(FileName, 'String to be appended', function(error) {
if (error)
console.error(error.message);
});

Using Grunt to Replace Text in a File

I'm trying to get Grunt to replace a path reference and I'm not sure what I'm doing wrong. This looks like it should work. Essentially, I'm copying a Bootstrap file up a directory and changing the #import paths, so I'm just trying to replace 'bootstrap/' with the new destination path 'MY/NEW/DEST/PATH/bootstrap'. I don't want to use a module for something as straight forward as this, seems needless. Everything works but the replace.
var destFilePath = path.join(basePath, file);
// Does the file already exist?
if (!grunt.file.exists(destFilePath)) {
// Copy Bootstrap source #import file to destination
grunt.file.copy(
// Node API join to keep this cross-platform
path.join(basePath, 'bootstrap/_bootstrap.scss'),
destFilePath
);
// Require node filesystem module, since not a global
var fs = require('fs');
// Replace #import paths to be relative to new destination
fs.readFile(destFilePath, 'utf8', function(err, data) {
// Check for any errs during read
if (err) {
return grunt.log.write(err);
}
var result = data.replace('/bootstrap\//g', 'bootstrap/bootstrap/');
fs.writeFile(destFilePath, result, 'utf8', function(err) {
return grunt.log.write(err);
});
});
}
You wrapped your regex in quotes - don't do that and it should work fine:
var result = data.replace(/bootstrap\//g, 'bootstrap/bootstrap/');

Is there an alternative to require() in Node.JS? A "soft require" which tries to find a file but doesn't error if it isn't there

I'm loading a config.json file using require('./config.json') but I don't want to require a config file if they want to pass command line arguments instead, or just use the defaults. Is there any way to try to load a JSON file this way but not spit out an error if it can't be found?
For general modules, you can check for existence before trying to load. In the following path is whatever path you want to load and process() is a function performing whatever processing you'd like on your module:
var fs = require("fs");
fs.exists(path, function (exists) {
if (exists) {
var foo = require(path);
process(foo);
}
else {
// Whatever needs to be done if it does not exist.
}
});
And remember that path above must be an actual path, and not a module name to be later resolved by Node as a path.
For a JSON file specifically, with path and process having the same meanings as above:
fs.readFile(path, function (err, data) {
if (err) {
// Whatever you must do if the file cannot be read.
return;
}
var parsed = JSON.parse(data);
process(parsed);
});
You can also use try... catch but keep in mind that v8 won't optimize functions that have try... catch in them. With path and process meaning the same as above:
try {
var foo = require(path);
process(foo);
}
catch (e) {
if (e.code !== "MODULE_NOT_FOUND")
throw e; // Other problem, rethrow.
// Do what you need if the module does not exist.
}

NodeJS: Asynchronous file read problems

New to NodeJS.
Yes I know I could use a framework, but I want to get a good grok on it before delving into the myriad of fine fine tools that are out there.
my problem:
var img = fs.readFileSync(path);
the above works;
fs.readFile(path, function (err, data)
{
if (err) throw err;
console.log(data);
});
the above doesn't work;
the input path is : 'C:\NodeSite\chrome.jpg'
oh and working on Windows 7.
any help would be much appreciated.
Fixed
Late night/morning programming, introduces errors that are hard to spot. The path was being set from two different places, and so the source path were different in both cases. Thankyou for your help. I am a complete numpty. :)
If you are not setting an encoding when reading a file, you will get the binary content.
So for example, the following snippet will output the content of the test file using UTF-8 encoding. If you don't use an encoding, you will get an output like "" on your console (raw binary buffer).
var fs = require('fs');
var path = "C:\\tmp\\testfile.txt";
fs.readFile(path, 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
});
Another issue (especially on windows-based OS's) can be the correct escaping of the target path. The above example shows how path's on Windows have to be escaped.
java guys will just use this javascript asynchronous command as if in pure java , troublefreely :
var fs = require('fs');
var Contenu = fs.readFileSync( fILE_FULL_Name , 'utf8');
console.log( Contenu );
That should take care of small & big files.

Resources