Access parameters
You can access command line parameters through process.argv, which is an array containing the following content:
[ nodeBinary, script, arg0, arg1, ... ]
In other words, the first parameter starts from process.argv[2], you can iterate through all parameters as follows:
process.argv.slice(2).forEach(function (fileName) {
...
});
If you want to do more complex processing of parameters, you can take a look at the Node.js modules nomnom and optimizer. Below, we will use the file system module many times:
var fs = require('fs');
Read one Text file
If your file is not very large, you can read the entire file into memory and put it into a string:
var text = fs.readFileSync(fileName, "utf8");
Then, you can split this text into one line Processing of one line.
text.split(/r?n /).forEach(function (line) {
// ...
});
For large files, you can use streams to iterate through all lines.mtomis in There is a solution on Stack Overflow.
Write a text file
You can write the complete content to a file through a string.
fs.writeFileSync(fileName, str , 'utf8');
Or you can write the string incrementally to the stream.
var out = fs.createWriteStream(fileName, { encoding: "utf8" });
out.write(str);
out.end( ); // Currently the same as destroy() and destroySoon()
Cross-platform considerations
Determine the line terminator.
Solution 1: Read an existing file Go to the string, search for "rn", and if not found, determine that the line terminator is "n".
var EOL = fileContents.indexOf("rn") >= 0 ? "rn" : "n";
Solution 2: Detection system Platform. All Windows platforms return "win32", as well as 64-bit systems.
var EOL = (process.platform === 'win32' ? 'rn' : 'n')
Handling paths
When processing file system paths You can use the path module. This ensures that the correct PATH delimiter is used ("/" on Unix, "" on Windows).
var path = require('path');
path.join(mydir, "foo");
Run the script
If your shell script is named myscript.js, then you can run it like this:
node myscript.js arg1 arg2 ...
On Unix , you can add a line of code to the first line of the script to tell the operating system what program should be used to interpret this script:
#!/usr/bin/env node
You must also Give the script executable permissions:
chmod u x myscript.js
Now the script can run independently:
./myscript.js arg1 arg2 ...
Other topics
-
Output to standard output (stdout): console.logThe same as in the browser. console is a global object, It is not a module, so there is no need to use require() to import .
-
Read standard input (stdin): process.stdin is a readable stream.process Is a global object.
-
Run shell command: through child_process.exec().
Related articles
- Tip: load source from a file in the Node.js shell
- Execute code each time the Node.js REPL starts